问题
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) 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))
The code above generates exceptions
2) Using Q objects:
hList = [Q(date__hour=h) for h in (16, 17, 18)]
MyModel.objects.filter(reduce(operator.or_, hList))
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
when instead the right raw SQL should be:
where extract(hour from date) in (16, 17, 18)
…how can I filter by hour range in an effective manner, without relying on raw sql?
回答1:
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)'])
回答2:
In Django 1.9+ you can chain hour lookups, so the examples from the question will work:
MyModel.objects.filter(date__hour__in=(16, 17, 18))
MyModel.objects.filter(date__hour__range=(16, 18))
来源:https://stackoverflow.com/questions/19958391/django-orm-filter-by-hour-range