Django Aggregation - Expression contains mixed types. You must set output_field

Lara picture Lara · Jul 23, 2016 · Viewed 14.5k times · Source

I'm trying to achive an Aggregation Query and that's my code:

TicketGroup.objects.filter(event=event).aggregate(
                           total_group=Sum(F('total_sold')*F('final_price')))

I have 'total_sold' and 'final_price' in TicketGroup object and all what I want to do is sum and multiply values to get the total sold of all TicketGroups together.

All I get is this error:

Expression contains mixed types. You must set output_field

What I am doing wrong, since I'm calling 'total_group' as my output field?

Thanks!

Answer

Todor picture Todor · Jul 23, 2016

By output_field Django means to provide field type for the result of the Sum.

from django.db.models import FloatField, F
total_group=Sum(F('total_sold')*F('final_price'), output_field=FloatField())

should do the trick.