Home > Back-end >  get sum based on another field django
get sum based on another field django

Time:05-16

I have these models:

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):
    
    ...
    

I want to make a property to display the sum of all investments inside the Offering model.

I did so like this:

    @property
    def amount_invested(self):
        return Investment.objects.filter(offering_id=self.id).aggregate(Sum('invested'))['invested__sum'] or 0

But, I also want to display the amount_invested iff the status inside the Investment model is 'received'.

May I know how I should be able to do this?

CodePudding user response:

You can filter the investment_set and thus only retain the Investments with status='received':

@property
def amount_invested(self):
    return self.investment_set.filter(
        status='received'
    ).aggregate(Sum('invested'))['invested__sum'] or 0
  • Related