Rhubarb
Rhubarb

Reputation: 308

How to Aggregate QuerySet for Arbitrary Keys Group By

<QuerySet [
    {'id': 520, 'Commission': None, 'Effective Date': '2019-12-11 00:00:00+00'},
    {'id': 520, 'Commission': 30, 'Effective Date': None}
]>

Suppose I had a Django QuerySet like the above, with an arbitrary number of matching keys where only one is expected to not be null per key.

How do I get a result like the following per id as if I'm grouping by id?

<QuerySet [
    {'id': 520, 'Commission': 30, 'Effective Date': '2019-12-11 00:00:00+00'}
]>

Upvotes: 0

Views: 139

Answers (1)

bmons
bmons

Reputation: 3392

You can use annotate method, refer the aggregation topic: https://docs.djangoproject.com/en/3.0/topics/db/aggregation/

Your_model.objects.values('id', 'date').annotate(total_commission=Sum('commission')).order_by('id'))

Upvotes: 1

Related Questions