How can I filter a date of a DateTimeField in Django?
I am trying to filter a DateTimeField
comparing with a date. I mean:
MyObject.objects.filter(datetime_attr=datetime.date(2009,8,22))
I get an empty queryset list as an answer because (I think) I am not considering time, but I want "any time".
Is there an easy way in Django for doing this?
I have the time in the datetime setted, it is not 00:00
.
Such lookups are implemented in django.views.generic.date_based
as follows:
{'date_time_field__range': (datetime.datetime.combine(date, datetime.time.min),
datetime.datetime.combine(date, datetime.time.max))}
Because it is quite verbose there are plans to improve the syntax using __date
operator. Check "#9596 Comparing a DateTimeField to a date is too hard" for more details.
YourModel.objects.filter(datetime_published__year='2008',
datetime_published__month='03',
datetime_published__day='27')
// edit after comments
YourModel.objects.filter(datetime_published=datetime(2008, 03, 27))
doest not work because it creates a datetime object with time values set to 0, so the time in database doesn't match.
Here are the results I got with ipython's timeit function:
from datetime import date
today = date.today()
timeit[Model.objects.filter(date_created__year=today.year, date_created__month=today.month, date_created__day=today.day)]
1000 loops, best of 3: 652 us per loop
timeit[Model.objects.filter(date_created__gte=today)]
1000 loops, best of 3: 631 us per loop
timeit[Model.objects.filter(date_created__startswith=today)]
1000 loops, best of 3: 541 us per loop
timeit[Model.objects.filter(date_created__contains=today)]
1000 loops, best of 3: 536 us per loop
contains seems to be faster.
链接地址: http://www.djcxy.com/p/6584.html上一篇: manytomany上的查询过滤器为空