Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django ORM, group by day

I am trying to group products by DAY, however date_created is a datetime field.

Product.objects.values('date_created') \
               .annotate(available=Count('available_quantity'))

returns:

[
    {'date_created': datetime.datetime(2012, 4, 14, 13, 3, 6), 'available': 1},
    {'date_created': datetime.datetime(2012, 4, 14, 17, 12, 9), 'available': 1},
    ...
]

I want:

[
    {'date_created': datetime.datetime(2012, 4, 14), 'available': 2}, ...
]

edit: database backend MYSQL

like image 274
Hedde van der Heide Avatar asked Apr 14 '12 14:04

Hedde van der Heide


2 Answers

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'))
like image 164
San4ez Avatar answered Sep 30 '22 21:09

San4ez


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'))
like image 37
Zanon Avatar answered Sep 30 '22 21:09

Zanon