Django: get the aggregated value of two multiplied columns

I need to get an aggregated value from two columns. Therefore, first several of them together, and then get their sum() . The code below naturally does not work, this is just for clarification.

Is it possible or should I use raw SQL?

 SomeModel.objects .filter(**something) .aggregate(Sum('one_column' * 'another_col')) 
+7
django django-orm django-aggregation
source share
3 answers

You do not need so much raw SQL using extra () .

 obj = SomeModel.objects.filter(**something).extra( select = {'total': 'SUM(one_column * another_column)'}, ) 
+10
source share

This is a Spartan. Thus, if you want to print it somewhere in the template, you should use something like this:

 {{ queryset.0.total }} 

Here answered correctly: Django Aggregation: Summing Multiplication of Two Fields

The form:

 agg = Task.objects.all().aggregate(total=Sum('field1', field="field1*field2")) 
+1
source share

As I replied here https://stackoverflow.com/a/168358/162035/ ... the correct solution depends on the version of django.

  • For django <1.8 use .aggregate(Sum('field1', field="field1*field2"))
  • For django> = 1.8 use .aggregate(Sum(F('field1')*F('field2'))
+1
source share

All Articles