Django ORM, group by day

2020-02-09 01:13发布

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

3条回答
爷、活的狠高调
2楼-- · 2020-02-09 01:37

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}, ...
]
查看更多
淡お忘
3楼-- · 2020-02-09 01:38

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'))
查看更多
乱世女痞
4楼-- · 2020-02-09 01:41

Inspired by this question try this for mysql

Product.objects.extra(select={'day': 'date( date_created )'}).values('day') \
               .annotate(available=Count('date_created'))
查看更多
登录 后发表回答