Django ORM: filter by hour range

2019-05-16 13:02发布

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?

2条回答
神经病院院长
2楼-- · 2019-05-16 13:44

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)'])
查看更多
神经病院院长
3楼-- · 2019-05-16 13:59

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))
查看更多
登录 后发表回答