Django Aggreagtion: Sum return value only?

I don't believe there is a way to get only the value.

You could just do ${{ total_paid.amount__sum }} in your template. Or do total_paid = Payment.objects.all().aggregate(Sum('amount')).get('amount__sum', 0.00) in your view.

EDIT

As others have pointed out, .aggregate() will always return a dictionary with all of the keys from the aggregates present, so doing .get() on the result is not necessary. However, if the queryset is empty, each aggregate value would be None. So depending on your code, if you are expecting a float, you could do:

total_paid = Payment.objects.all().aggregate(Sum('amount'))['amount__sum'] or 0.00


Give it a name and then ask for it:

total_paid = Payment.objects.all.aggregate(sum=Sum('amount'))['sum']

Should be little more readable, and there is no need for conversion.


The aggregate() method returns a dictionary. If you know you're only returning a single-entry dictionary you could use .values()[0].

In Python 2:

total_paid = Payment.objects.aggregate(Sum('amount')).values()[0]

In Python 3, (thanks @lmiguelvargasf) this will need to be:

total_paid = list(Payment.objects.aggregate(Sum('amount')).values())[0]

The end result is the same as @jproffitt's answer, but it avoids repeating the amount__sum part, so it's a little more generic.