2

I need to calculate the sumproduct of two fields from Django queryset.

I have checked the answer in Django Aggregation: Summation of Multiplication of two fields but it doesnt work. They suggest the following code for django < 1.8:

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

which returns the sum of the 'field1' not the defined field="field1*field2"

and for django >= 1.8

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

which returns TypeError: Complex aggregates require an alias

Mike
  • 369
  • 5
  • 21

1 Answers1

4

Try something like this

from django.db.models import Sum, F
MyModel.objects.filter(<filters>).aggregate(sum=Sum(F('field1')*F('field2')))["sum"]
Umair Mohammad
  • 4,489
  • 2
  • 20
  • 34
  • Tried it right now. I get the FieldError: Expression contains mixed types. You must set output_field. – Mike Feb 07 '19 at 10:35
  • 1
    Thanks it worked. I searched this error and resolved it through https://stackoverflow.com/questions/38546108/django-aggregation-expression-contains-mixed-types-you-must-set-output-field – Mike Feb 07 '19 at 10:40