akrisanov akrisanov - 3 days ago 6
Python Question

Sum records values in Django

I defined couple models in my app:

class Project(models.Model):
title = models.CharField(max_length=150)
url = models.URLField()
manager = models.ForeignKey(User)

class Cost(models.Model):
project = models.ForeignKey(Project)
cost = models.FloatField()
date = models.DateField()

I want to sum costs for each project and render values

from mypm.costs.models import Project, Cost
from django.shortcuts import render_to_response
from django.db.models import Avg, Sum

def index(request):
# ...
return render_to_response('index.html',...

What is the best way of solving such aggregation in Django ORM?

Answer Source

Alexander's solution will give you the right result, but with one query for each project. Use annotate to do the whole thing in a single query.

from django.db.models import Sum

annotated_projects = Project.objects.all().annotate(cost_sum=Sum('cost__cost'))
for project in annotated_projects:
    print project.title, project.cost_sum