I have a QuerySet of OrderItem objects. They are in the form of:
OrderItem
- ID
- BillingParty
- Rate
I want to aggregate / GROUP BY by QuerySet, such that it orders by the highest combined rate and annotates the rate and count. Here's an illustration
- 1
- Paramount
- 500
- 2
- WB
- 300
- 3
- Paramount
- 400
From this, I want to be able to get:
[
{'BillingParty': 'Paramount', 'TotalRate': 900, 'ItemCount': 2},
{'BillingParty': 'WB', 'TotalRate': 300, 'ItemCount': 1},
]
How would I do this? I was thinking it would be something like:
order_items.aggregate('billing_party')
.annotate(ItemCount=Count('id'), TotalRate=Sum('rate')
Or, is it too complex for django and I need to do a python for loop here to add in the stuff.