Django Aggregate Query Values for Multiple Objects

1.2k views Asked by At

In my project I have a model called Organization that can have multiple Campaign's. Each campaign can then have multiple donor's. Hopefully to clarify here is what my models look like:

class Campaign(models.Model):
    name = models.CharField()
    organization = models.ForeignKey('org.Organization')


class Donor(models.Model):
    lead = models.ForeignKey('org.Lead')
    amount = models.DecimalField()
    campaign = models.ForeignKey(Campaign)

What I would like to do is show a campaign, then display the sum of all amounts made by donors (donor.amount). So for example, if "Campaign1" has three donors, each of whom donated $5, in my template it will show: "Campaign1: $15."

Any idea on how I can accomplish this? I was thinking about using a backward relationship in my template but you can not create Aggregates this way. Thanks for any help.

2

There are 2 answers

0
NS0 On BEST ANSWER

You should be able to use annotate to get this information. Try something like:

from django.db.models import Sum    
campaigns = Campaign.objects.annotate(total_donations=Sum('donor__amount'))

You can then access the total donations for each campaign:

for campaign in campaigns:
    print "%s: $%s" % (campaign.name, campaign.total_donations)
0
Mauricio Cortazar On

you can try:

from django.db.models import
a = Campaign.objects.get(pk=1)
a.annotate(total_donnation=Sum('donor__amount'))