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

26,241

Solution 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.

Solution 2

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/

Share:
26,241

Related videos on Youtube

Lara
Author by

Lara

Full Stack Developer.

Updated on June 21, 2020

Comments

  • Lara
    Lara about 4 years

    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!