Django/Python-查询计算字段

Django/Python-查询计算字段,python,django,django-models,sum,aggregate,Python,Django,Django Models,Sum,Aggregate,我有下面的模型,希望对分配的外键进行计算,然后对金额求和 class Fundraising(models.Model): @property def amount_raised(self): amount_raised = FundraisingDonation.objects.filter( fundraising_event=self, ).agg

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

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)),但这似乎也不起作用?

您不能在
@属性上聚合,因为该属性在数据库端是未知的

您可以做的是组织机构的查询集,例如:

from django.db.models import F, Sum

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

您不能在
@属性
上进行聚合,因为该属性在数据库端是未知的

您可以做的是组织机构的查询集,例如:

from django.db.models import F, Sum

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

谢谢虽然不确定这种方法是否有效,因为筹集的金额也是一个属性字段?我还需要能够将total属性与其他两个total属性相加,得到一个总的total属性(即Summedtotals=TotalA+TotalB+TotalC-因此,如果这只是一个注释属性,我将无法将结果添加到任何其他内容中?@Oliver:你能分享你的
筹款捐赠
模型的相关部分吗?用每个模型的相关部分更新了问题-我基本上需要进行计算(合计)在计算中(@property def total)在计算中(fundraising.allocation.amount_raised)!@Oliver:the
fundraising捐赠有一个
ForeignKey
to
fundraising
?是的,这是正确的。fundraising捐赠还有这个字段:fundraising\u event=models.ForeignKey(fundraising,on\u delete=models.CASCADE)谢谢。虽然不确定这种方法是否有效,因为“筹集的金额”也是一个属性字段?但我还需要能够将“总计”属性与其他两个“总计”属性相加,得到一个总计(即Summedtotals=TotalA+TotalB+TotalC-因此,如果这只是一个注释属性,我将无法将结果添加到任何其他内容中?@Oliver:你能分享你的
筹款捐赠
模型的相关部分吗?用每个模型的相关部分更新了问题-我基本上需要进行计算(合计)在计算中(@property def total)在计算中(fundraising.allocation.amount_raised)!@Oliver:the
fundraising捐赠有一个
ForeignKey
to
fundraising
?是的,这是正确的。fundraising捐赠还有这个字段:fundraising\u event=models.ForeignKey(fundraising,on\u delete=models.CASCADE)