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!
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.
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With