tags:

views:

66

answers:

3

I have a two Model - Project and Cost.

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 must return the sum of costs for each project. 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',...

How?

+2  A: 

Try using aggregate.

from django.db.models import Sum

for project in Projects.objects.all():
  print project, project.cost_set.all().aggregate(sum_of_cost=Sum('cost'))['sum_of_cost'] or 0
Alexander Ljungberg
+2  A: 

Here's one way to do it. There may be a more efficient way to write the get_total_cost function... but this should work.

Models:

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

    def get_total_cost(self):
        tot = 0
        for cost in Cost.objects.filter(project=self):
            tot += cost.cost
        return tot

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

View:

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',{'projects',Project.objects.all()},context_instance=RequestContext(request))

Template:

{% for project in projects %}
<p>{{project.title}}: {{project.get_total_cost}}</p>
{% endfor %}

This is pretty basic stuff.

Take some time and go through the Django tutorials and documentation.

Brant
+3  A: 

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
Daniel Roseman