pythondjango

How to sum only positive values, with Django conditional aggregates?


I have a table that looks like this:

class MeasureValue(models.Model):
    cost_saving_10th = models.FloatField(null=True, blank=True)

I know how to get the sum of all the values:

mvs.aggregate(Sum('cost_saving')).values()[0]

But how do I get the sum of all the positive values? I think I need a conditional aggregate, but I'm not sure how to do this.


Solution

  • You can filter the queryset before you aggregate to remove any values that are less than or equal to 0 with __gt (__gte would include 0's which just makes more work for the summation)

    mvs.filter(cost_saving_10th__gt=0).aggregate(Sum('cost_saving_10th'))
    

    Note: Since you're filtering the queryset, you may lose entries from the queryset's results.