[Fixed]-Django. How to aggregate amounts by payers group

1👍

Using annotate and Sum/Count, you can do a lot of aggregations queries. Here’s the queries for your examples:

from django.db.models import Sum
# 1. Get total of transactions per payer, ranked by total
Transactions.objects.values('payer').annotate(total=Sum('amount')) \
                    .order_by('-total')
# 2. Get total per payer/receiver, ranked by total
Transactions.objects.values('payer', 'receiver').annotate(total=Sum('amount')) \
                    .order_by('-total')

You will get a list of dict as result (since it can’t match your model), so if payer and/or receiver is a ForeignKey, don’t forget to get the proper attribute to retrieve the name (or do a separate query to get their full object)

Leave a comment