DJango ORM: Sum of multiplication

Consider the following model:

class Task(models.Model):
   progress = models.PositiveIntegerField()
   estimated_days = models.PositiveIntegerField()

Now to calculate sum of progress*estimated_days follow this:

from django.db.models import Sum

total = Task.objects.filter(your-filter-here).aggregate(total=Sum('progress', field="progress*estimated_days"))['total']

Note: if two fields are of different types, say integer & float, the type you want return should be passed as the first parameter of Sum.

Leave a Reply