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?
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 akeyfunction 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 Pythondatetimemethoddate()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!):