1

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.

ng150716
  • 2,195
  • 5
  • 40
  • 61

2 Answers2

4

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)
NS0
  • 6,016
  • 1
  • 15
  • 14
0

you can try:

from django.db.models import
a = Campaign.objects.get(pk=1)
a.annotate(total_donnation=Sum('donor__amount'))
Mauricio Cortazar
  • 4,049
  • 2
  • 17
  • 27