Django Aggregation - Expression contains mixed typ

2019-03-19 10:03发布

问题:

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!

回答1:

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.