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

末鹿安然 提交于 2019-12-04 09:11:00

问题


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.




回答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/



来源:https://stackoverflow.com/questions/38546108/django-aggregation-expression-contains-mixed-types-you-must-set-output-field

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!