Django Aggregation: Summation of Multiplication of two fields

Raunak Agarwal picture Raunak Agarwal · Aug 28, 2012 · Viewed 36.5k times · Source

I have a model something like this:

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

Now I would like to do a calculation Sum(progress * estimated_days) on the database level. Using Django Aggregation I can have the sum for each field but not the summation of multiplication of fields.

Answer

kmmbvnr picture kmmbvnr · Jun 22, 2015

With Django 1.8 and above you can now pass an expression to your aggregate:

 from django.db.models import F

 Task.objects.aggregate(total=Sum(F('progress') * F('estimated_days')))['total']

Constants are also available, and everything is combinable:

 from django.db.models import Value

 Task.objects.aggregate(total=Sum('progress') / Value(10))['total']