根据另一个字段 django 获取总和
get sum based on another field django
我有这些型号:
status_choices = ['not received', 'received']
class Investment(Model):
# Offering
offering = models.ForeignKey(Offering, blank=False, null=False, on_delete=models.CASCADE)
invested = models.DecimalField(max_digits=9, default=0, decimal_places=2, blank=True, null=True)
status = models.CharField(max_length=200, choices=status_choices, blank=True, null=True, default='not received')
class Offering(Model):
...
我想制作一个 属性 来显示 Offering
模型中所有投资的总和。
我是这样做的:
@property
def amount_invested(self):
return Investment.objects.filter(offering_id=self.id).aggregate(Sum('invested'))['invested__sum'] or 0
但是,我还想显示 amount_invested
当且仅当 Investment
模型中的 status
是 'received'
。
我可以知道我应该怎么做吗?
您可以过滤 investment_set
,从而仅保留 status='received'
的 Investment
:
@property
def amount_invested(self):
return self.investment_set.filter(
<strong>status='received'</strong>
).aggregate(Sum('invested'))['invested__sum'] or 0
我有这些型号:
status_choices = ['not received', 'received']
class Investment(Model):
# Offering
offering = models.ForeignKey(Offering, blank=False, null=False, on_delete=models.CASCADE)
invested = models.DecimalField(max_digits=9, default=0, decimal_places=2, blank=True, null=True)
status = models.CharField(max_length=200, choices=status_choices, blank=True, null=True, default='not received')
class Offering(Model):
...
我想制作一个 属性 来显示 Offering
模型中所有投资的总和。
我是这样做的:
@property
def amount_invested(self):
return Investment.objects.filter(offering_id=self.id).aggregate(Sum('invested'))['invested__sum'] or 0
但是,我还想显示 amount_invested
当且仅当 Investment
模型中的 status
是 'received'
。
我可以知道我应该怎么做吗?
您可以过滤 investment_set
,从而仅保留 status='received'
的 Investment
:
@property
def amount_invested(self):
return self.investment_set.filter(
<strong>status='received'</strong>
).aggregate(Sum('invested'))['invested__sum'] or 0