I have a list of values paid and want to display the total paid. I have used Aggregation and Sum to calculate the values together. The problem is,I just want the total value printed out, but aggreagtion prints out: {'amount__sum': 480.0}
(480.0 being the total value added.
In my View, I have:
from django.db.models import Sum
total_paid = Payment.objects.all.aggregate(Sum('amount'))
And to show the value on the page, I have a mako template with the following:
<p><strong>Total Paid:</strong> ${total_paid}</p>
How would I get it to show 480.0
instead of {'amount__sum': 480.0}
?
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 dototal_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 beNone
. 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
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:
In Python 3, (thanks @lmiguelvargasf) this will need to be:
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.In Python 3:
You can solve it by converting the
dict_values
to alist
:The previous code avoids using
'column_name__sum'
as key, but in case you prefer the dictionary way:In terms of efficiency, I made a test with some data I have, and it seems that using the dictionary key is faster:
In terms of readability, I think that @mehmet's solution is the best one, and I have also test its efficiency:
Give it a name and then ask for it:
Should be little more readable, and there is no need for conversion.