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.
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)