我有下面的模型,希望对分配的外键进行计算,然后对金额求和
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)),但这似乎也不起作用
无法在
@property
上进行聚合,因为该属性在数据库端是未知的您可以做的是^{} [Django-doc]查询
Organisation
的查询集,例如:由此查询集产生的每个}项的
Organisation
都将有一个名为.total
的额外属性,该属性包含与percentshare
相乘的相关{amount_raised
值之和编辑:由于
amount_raised
是一个属性,我们需要在FundraisingDonation
模型上进行聚合,因此:相关问题 更多 >
编程相关推荐