Django 选择查询时间差异
我正在尝试使用以下列等查询 django 中的数据库表:
id | start_time | end_time
我可以直接在查询中获取差异,而不是获取两者的单独值吗? 有这样的效果:
SELECT id, Diff(start_time, end_time) FROM myTable
I am trying to query a database table in django with, among others, the following columns:
id | start_time | end_time
Rather than getting the separate values for the two, can I just get the difference directly in a query?
Something to this effect:
SELECT id, Diff(start_time, end_time) FROM myTable
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
QuerySet.extra()
将允许您为列指定任意表达式。请注意,结果将取决于数据库。QuerySet.extra()
will allow you to specify arbitrary expressions for a column. Note that the result will be DB-dependent.在我看来,最简单的方法是添加第三列,并在每次修改对象时更新它,如下所示:
我试图寻找带有注释的解决方案,但是 mysql 中都不支持聚合函数也不是 postgres。即使在那里,似乎很好地权衡了一个额外的列,而不必计算每个查询中每一行的差异!
哦,你可以像这样检索你想要的东西:
It seems to me that the easiest way is to add a third column with the difference and update it every time the object is modified like this:
I tried to look for a solution with annotate, but there is no support for aggregate functions in either mysql nor postgres. Even if there where, seem like nice trade off an extra column for not having to calculate the diff for each row on each query!
Oh, and you can just retrieve what you want like this:
从 Django 1.8 开始,不鼓励使用
extra
< /a> 支持注释
+RawSQL
。以下适用于 MySQL:As of Django 1.8,
extra
is discouraged in favor ofannotate
+RawSQL
. The following works for MySQL:这可以完全通过 Django 1.10 及以上。使用这样的模型:
您可以使用持续时间来注释对象,如下所示:
This can be done entirely through the ORM in Django 1.10 and above. With a model like so:
You can annotate the objects with the duration like so: