Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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!

like image 317
Lara Avatar asked Jul 23 '16 20:07

Lara


2 Answers

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.

like image 158
Todor Avatar answered Oct 04 '22 12:10

Todor


I had to use something different in order to make my query work. Just output_field wont solve it. I needed a simple division between two aliases. These are output of two annotations.

from django.db.models import FloatField, ExpressionWrapper, F

distinct_people_with_more_than_zero_bill = Task.objects.filter(
    billable_efforts__gt=0).values('report__title').annotate(
    Count('assignee', distinct=True)).annotate(
    Sum('billable_efforts'))

annotate(yy=ExpressionWrapper(F('billable_efforts__sum') / F('assignee__count'), output_field=FloatField()))

The key here is ExpressionWrapper. Without this, you will get an error: received non-expression(s)

The hint came for Django documentation itself, which says:

If the fields that you’re combining are of different types you’ll need to tell Django what kind of field will be returned. Since F() does not directly support output_field you will need to wrap the expression with ExpressionWrapper

Link: https://docs.djangoproject.com/en/2.2/ref/models/expressions/

like image 44
Arindam Roychowdhury Avatar answered Oct 04 '22 14:10

Arindam Roychowdhury