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 view.py:
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?
Alexander’s solution will give you the right result, but with one query for each project. Use
annotateto do the whole thing in a single query.