Django model timerange filtering method

时光怂恿深爱的人放手 提交于 2019-12-02 03:36:15

问题


I saw the next two methods in an old question here but it is not clear for me what is the difference between:

{'date_time_field__range': (datetime.datetime.combine(date, datetime.time.min),
                        datetime.datetime.combine(date, datetime.time.max))}

and

YourModel.objects.filter(datetime_published__year='2008', 
                     datetime_published__month='03', 
                     datetime_published__day='27')

回答1:


Was confused about this myself, but I think I've worked it out :-D I found the documentation about the range lookup option very helpful.

When you do:

YourModel.objects.filter(datetime_published__year='2008', 
                     datetime_published__month='03', 
                     datetime_published__day='27')

The SQL will look something like:

SELECT ... WHERE EXTRACT('year' FROM pub_date) = '2008'
             AND EXTRACT('month' FROM pub_date) = '03'
             AND EXTRACT('day' FROM pub_date) = '27';

Whereas this part of django's generic date based views:

{'date_time_field__range': (datetime.datetime.combine(date, datetime.time.min),
                        datetime.datetime.combine(date, datetime.time.max))}

becomes something like:

YourModel.objects.filter(datetime_published__range=(
                datetime.datetime.combine('2008-03-27',datetime.time.min),
                datetime.datetime.combine('2008-03-27',datetime.time.max)
                                                                  )

which produces SQL along the lines of:

SELECT ... WHERE datetime_published BETWEEN '2008-03-27 00:00:00'
                                        AND '2008-03-27 23:59:59';

(the format of the timestamp in the last SQL example is wrong obviously, but you get the idea)

Hope that answers your question :)



来源:https://stackoverflow.com/questions/3043859/django-model-timerange-filtering-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!