How to use the Django ORM to query only by date in a datetimefield
I have a table with a DataTimeField. I'd like to get a list of all the objects where the DateTimeField =开发者_如何学C a specific day (ignoring the time part).
The SQL would look something like:
select * from tblname where date(start)='2011-01-14'
Is it possible to get the ORM to do this kind of query?
I can do a start__range(...) kind of query, but I was wondering if I could do it the other way.
From the QuerySet API reference:
Entry.objects.filter(pub_date__year=2005)
Entry.objects.filter(pub_date__month=12)
Entry.objects.filter(pub_date__day=6)
This works for Dates and DateTimes.
MyModel.object.filter(start__year=2011, start__month=01, start__day=14)
the problem with this query is that if your DB dont suport index with functions (Hello MySQL) you have an inneficient query.
One alternative can be that you add a new field start_date = models.DateField(...)
and overload your save(...)
method to set the field correctly, or if you are more a database side dev, use a trigger for the same function, after this, you can do:
MyModel.object.filter(start_date=date(2011, 1, 13))
精彩评论