Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sum this query set element in Django template?

I have a function to view report:

def view_report(request):
    a = Bill.objects.all()
    return render_to_response('report.html', {'a':a}, context_instance=RequestContext(request))

There's a attribute called price which has numeric elements. I want to sum all the prices and show as one number in Django template:

{% for i in a %}

{{ i.price }}

{% endfor %}

This simply returns all the prices. I want to sum all those prices and show as one. I tried using {{ i.price|sum }} which didn't work.

like image 271
user1881957 Avatar asked Nov 19 '25 01:11

user1881957


1 Answers

Don't do that in the template. Use the aggregation API in your view:

from django.db.models import Sum
total_price = Bill.objects.all().aggregate(Sum('price'))
like image 190
Daniel Roseman Avatar answered Nov 21 '25 16:11

Daniel Roseman