django:datediff sql 查询?
我正在尝试在 Django 中执行与以下 SQL 相同的操作:
SELECT * FROM applicant WHERE date_out - date_in >= 1 AND date_out - date_in <= 6
我可以将其作为 RAW sql 查询来执行,但是在处理 RawQuerySet 而不是常规 QuerySet 对象时,这变得令人沮丧,因为我希望能够过滤稍后在代码中。
I'm trying to do the equivalent of the following SQL in Django:
SELECT * FROM applicant WHERE date_out - date_in >= 1 AND date_out - date_in <= 6
I can do this as a RAW sql query, but this is becoming frustrating in dealing with a RawQuerySet instead of a regular QuerySet object as I would like to be able to filter it later in the code.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我遇到了 Django 本身不支持
Datediff
(以及其他数据库等效项)的问题,并且需要针对特定项目多次使用这样的函数。经过进一步阅读,很明显,计算两个日期间隔的实现在主要数据库风格之间存在很大差异。这可能就是 Django 中还没有原生抽象函数的原因。所以我为
datediff
编写了自己的 Django ORM 函数:请参阅:mike-db-tools Github 存储库
您将看到在各个数据库的文档字符串中编写的数据库后端之间不同的语法。 Datediff 支持 sqlite、MySQL / MariaDB、PostgreSQL 和 Oracle。
用法(Django 1.8+):
当涉及到我的代码时,我真的很傻,所以我鼓励你分叉和改进。
I came across the issue of Django not natively supporting
Datediff
(and other database equivalents), and needed to use such a function many times for a particular project.Upon further reading, it became clear that the implementation of calculating an interval from two dates differs widely between major database flavours. This is probably why it's not got a native abstraction function in Django yet. So I wrote my own Django ORM function for
datediff
:See: mike-db-tools Github repository
You'll see the varying syntax between the database backends written in the docstrings for the respective databases. Datediff supports sqlite, MySQL / MariaDB, PostgreSQL and Oracle.
Usage (Django 1.8+):
I'm really quite derpy when it comes to my code, so I encourage you to fork and improve.
您可以使用
extra()
方法并传入where
关键字参数。where
的值应该是一个包含上述查询的 SQLWHERE
子句的列表。我使用 Postgresql 8.4 对此进行了测试,这就是我的情况:这将返回一个有效的 QuerySet 实例。
You can use the
extra()
method and pass in awhere
keyword argument. The value ofwhere
should be a list that contains the SQLWHERE
clause of the query above. I tested this with Postgresql 8.4 and this is what it looked like in my case:This will return you a valid
QuerySet
instance.