#StackBounty: #python #django #django-models Django annotate group by date return object

Bounty: 50

I’m using Django’s annotate from the aggregate doc.

My goal is to group a model by date and return all objects associated with each date in this form:

[{
  'date': datetime.datetime(2019, 6, 22, 11, 35), 
  'instances': [<Model: (1)>, <Model: (2)>  ]
},
{
  'date': datetime.datetime(2019, 6, 21, 11, 35),
  'instances': [<Model: (3)>, <Model: (6)>  ]
},]

I tried this query:

Flight.objects.values('origin_scheduled_dep').annotate(Count('origin_scheduled_dep')).order_by('origin_scheduled_dep')

But that’s returning the values I specified:

<QuerySet [{'origin_scheduled_dep': datetime.datetime(2019, 6, 22, 11, 35), 'origin_scheduled_dep__count': 1}, {'origin_scheduled_dep': datetime.datetime(2019, 6, 22, 15, 40), 'origin_scheduled_dep__count': 1}, {'origin_scheduled_dep': datetime.datetime(2019, 6, 22, 22, 0), 'origin_scheduled_dep__count': 2}]>

Thanks for any help, always 🙂


Get this bounty!!!

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.