Django/Python查询计算字段

2024-10-02 20:38:51 发布

您现在位置:Python中文网/ 问答频道 /正文

我有下面的模型,希望对分配的外键进行计算,然后对金额求和

class Fundraising(models.Model):
    @property
    def amount_raised(self):
        amount_raised = FundraisingDonation.objects.filter(
                            fundraising_event=self,
                            ).aggregate(donationamount=Coalesce(Sum('donationamount'), 0.00))['donationamount']
        return amount_raised

class FundraisingDonation(models.Model):
    donationamount = models.DecimalField(max_digits=11, decimal_places=2, default=0)


class Testmodel(models.Model):
      organisation = models.ForeignKey(Organisation, on_delete=models.CASCADE)
      allocation = models.ForeignKey(Fundraising, on_delete=models.CASCADE, related_name='items')
      percentshare = models.DecimalField(max_digits=11, decimal_places=2, default=0) #SET BY USER

     @property
     def amount(self):
         amount = self.allocation.amount_raised * self.percentshare
         return amount

上面的“金额”模型属性计算每个模型实例的金额字段

我现在尝试在一个新的模型上总结每个组织的金额,但是以下方法不起作用,因为我不相信我可以在计算字段上运行查询

class Totals(models.Model):
    totals = total + totalB + totalC
    @property
    def total(self):
        total = Testmodel.objects.filter(
                           organisation=self.organisation
                            ).aggregate(amount=Coalesce(Sum('amount'), 0.00))['amount']

有没有办法修改最后一行以使其生效,或者重新形成这一行中的计算?我还尝试了聚合(Sum(amount_raised*percentshare)),但这似乎也不起作用


Tags: 模型selfmodelmodelsdefproperty金额amount
1条回答
网友
1楼 · 发布于 2024-10-02 20:38:51

无法在@property上进行聚合,因为该属性在数据库端是未知的

您可以做的是^{} [Django-doc]查询Organisation的查询集,例如:

from django.db.models import F, Sum

Organisation.objects.annotate(
    total=Sum(
        F('testmodel__allocation__amount_raised') * F('testmodel__percentshare')
    )
)

由此查询集产生的每个Organisation都将有一个名为.total的额外属性,该属性包含与percentshare相乘的相关{}项的amount_raised值之和

编辑:由于amount_raised是一个属性,我们需要在FundraisingDonation模型上进行聚合,因此:

from django.db.models import F, Sum, Value
from django.db.models.functions import Coalesce

Organisation.objects.annotate(
    total=Coalesce(Sum(
        F('testmodel__allocation__fundraising__donationamount') *
        F('testmodel__percentshare'), Value(0))
    )
)

相关问题 更多 >