Django Aggregation: Summation of Multiplication of two fields Django Aggregation: Summation of Multiplication of two fields python python

Django Aggregation: Summation of Multiplication of two fields


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']


Update: for Django >= 1.8 please follow the answer provided by @kmmbvnr

it's possible using Django ORM:

here's what you should do:

from django.db.models import Sumtotal = ( Task.objects            .filter(your-filter-here)            .aggregate(                total=Sum('progress', field="progress*estimated_days")             )['total']         )

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

It's a late answer, but I guess it'll help someone looking for the same.


The solution depends on Django version.

  • django < 1.8

    from django.db.models import SumMyModel.objects.filter(<filters>).aggregate(Sum('field1', field="field1*field2"))
  • django >= 1.8

    from django.db.models import Sum, FMyModel.objects.filter(<filters>).aggregate(Sum(F('field1')*F('field2')))