MyModel.objects.filter(created_at__gte='2011-03-09', created_at__lte='2011-03-11').values('created_at','status').annotate(status_count=Count('status'))
The above query has the problem with the created_at
datetime field. Is it possible to tune the above query to ignore the time value and use the date value alone while performing group by?
Yes, that's possible using 'extra' and DB-level date formatting functions. Implementation can be found in e.g. django-qsstats-magic package.
You can do it easily using extra keyword in django.
date_trunc is postgres function it takes, only precision specified.
I'm too late for this question, but for future reference, I want to point out that this is actually possible with native Django, as described at https://stackoverflow.com/a/2283913
I am not sure whether Django's ORM can perform a conversion of datetimes to dates in the middle of a query. You could, though, do the query first, get the results, then use the Python
groupby()
function to sort out the rows that are returned. Here is a small example of grouping datetimes by date:As you can see, you have to provide
groupby()
with akey
function that takes one of the objects that it is grouping and extracts the value by which the grouping should take place — in this case, it grabs the second item in each row with[1]
and then calls the Pythondatetime
methoddate()
on it to extract the date part without the hours and minutes. The output of the script looks like this (thepprint()
function is just a fancy "print" statement that indents the output, it won't be needed in your Django code!):