Django ORM, group by day
Inspired by this question try this for MySQL
from django.db.models import Count
Product.objects.extra(select={'day': 'date( date_created )'}).values('day') \
.annotate(available=Count('date_created'))
In Django 1.4, you could use .dates('date_created', 'day')
instead of .values()
.
Try this code snippet:
Product.objects.annotate(available=Count('available_quantity')) \
.dates('date_created', 'day')
This should return:
[
{'date_created': datetime.datetime(2012, 4, 14), 'available': 2}, ...
]
Similar approach from San4ez's answer, but returning dates as 'YYYY-MM-DD' instead of 'datetime.datetime(YYYY, MM, DD)':
Product.objects.extra(select={'day': "TO_CHAR(date_created, 'YYYY-MM-DD')"})
.values('day') \
.order_by('day') \
.annotate(available=Count('date_created'))