django:datediff sql查询吗? [英] django: datediff sql queries?
问题描述
我正在尝试在Django中执行以下SQL:
I'm trying to do the equivalent of the following SQL in Django:
SELECT * FROM申请人WHERE date_out-date_in> = 1 AND date_out-date_in< = 6
SELECT * FROM applicant WHERE date_out - date_in >= 1 AND date_out - date_in <= 6
我可以作为RAW sql查询来执行此操作,但是在处理RawQuerySet而不是常规QuerySet对象时,这变得令人沮丧,因为我希望能够以便稍后在代码中对其进行过滤。
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.
推荐答案
您可以使用 extra()
方法并传入 where
关键字参数。 其中
的值应为包含上面查询的SQL WHERE
子句的列表。我使用Postgresql 8.4进行了测试,这就是我的情况:
You can use the extra()
method and pass in a where
keyword argument. The value of where
should be a list that contains the SQL WHERE
clause of the query above. I tested this with Postgresql 8.4 and this is what it looked like in my case:
q = Applicant.objects.extra(where = ["""date_part('day', age(date_out, date_in)) >= 1 and
date_part('day', age(date_out, date_in)) <= 6"""])
这将返回一个有效的 QuerySet
实例。
This will return you a valid QuerySet
instance.
这篇关于django:datediff sql查询吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!