Django ORM:按小时范围过滤 [英] Django ORM: filter by hour range
问题描述
我正在尝试为小时范围实施过滤器,它应该返回日期在hourA和hourB之间的记录(即:给我保存在16pm和18pm之间保存的记录)。
我的尝试:
I'm trying to implement a filter for hour range, it should returns records with a date between hourA and hourB (ie: "give me the records saved between 16pm and 18pm"). My attempts:
1)使用新的1.6 __ hour
过滤器和 __ in
或 __ range
:
1) Using new 1.6 __hour
filter and __in
or __range
:
MyModel.objects.filter(date__hour__in=(16, 17, 18))
MyModel.objects.filter(date__hour__range=(16, 18))
上面的代码生成异常
2)使用Q对象:
hList = [Q(date__hour=h) for h in (16, 17, 18)]
MyModel.objects.filter(reduce(operator.or_, hList))
此版本有效,但效率很低,因为它在范围内的每一小时都会重复执行extract()通过生成如下内容进行调用:
This version works, but is very inefficient, since for each hour in the range it repeats the extract() call by generating something like:
where
extract(hour from date) = 16 or
extract(hour from date) = 17 or
extract(hour from date) = 18
正确的原始SQL应该是:
when instead the right raw SQL should be:
where extract(hour from date) in (16, 17, 18)
...如何在不依赖原始sql的情况下有效地按小时范围过滤?
…how can I filter by hour range in an effective manner, without relying on raw sql?
推荐答案
我设法通过以下方式解决了该问题:
I managed to solve the issue in this way:
all_points = MyModel.objects.all()
all_points.extra(where=['extract(hour from MyDateField) in (16, 17, 18)'])
这篇关于Django ORM:按小时范围过滤的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!