简体   繁体   English

使用django中的另一个模型在模型中求和金额字段

[英]sum amount field in model using another model in django

I have three models: User, Campaign and Donation.我有三个模型:用户、活动和捐赠。 The donation model has a donation amount, donated by each user against each campaign.捐赠模型有一个捐赠金额,由每个用户针对每个活动捐赠。

Campaign model活动模型

class Campaign(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    # this is many to one relationship, on_deleting user, profile will also be deleted
    campaign_title = models.CharField(max_length=200, blank=True)

Donation model捐赠模式

class Donation(models.Model):
    user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True)
    # this is many to one relationship, on_deleting user, user's donation details will be set to NULL
    campaign = models.ForeignKey(Campaign, on_delete=models.DO_NOTHING)
    donation_amount = models.IntegerField()

views.py file视图.py 文件

def landing_page(request):
    # campaigns = Campaign.objects.all().order_by('-id')
    campaigns = Campaign.objects.all().order_by('-id')

    ////DO SOMETHING HERE TO SHOW TOTAL DONATION AGAINST EACH CAMPAIGN////

    return render(request, 'core/landing_page.html',{'campaigns':campaigns})

Using the current views.py file, I'm able to display all the campaigns, how do I pass the total donation against each campaign to the html file?使用当前的 views.py 文件,我可以显示所有活动,如何将每个活动的总捐款传递给 html 文件?

You can use annotate like this.您可以像这样使用注释。

from django.db.models import Sum

campaigns = Campaign.objects.annotate(donations=Sum('donation__donation_amount'))

Every compaign object will have a donations attribute with value to sum of total donations for that compaign.每个活动对象都将有一个donations属性,其值为该活动的总捐赠总额。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM