Django 聚合 - 表达式包含混合类型。您必须设置 output_field

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

我正在尝试实现聚合查询,这是我的代码:

TicketGroup.objects.filter(event=event).aggregate(
                           total_group=Sum(F('total_sold')*F('final_price')))

我在 TicketGroup 对象中有 'total_sold' 和 'final_price',我想做的就是对值求和并相乘以获得所有 TicketGroup 的总销售量。

我得到的只是这个错误:

Expression contains mixed types. You must set output_field

我做错了什么,因为我调用 'total_group' 作为我的输出字段?

谢谢!

Django通过output_field的方式为Sum.

的结果提供字段类型
from django.db.models import FloatField, F
total_group=Sum(F('total_sold')*F('final_price'), output_field=FloatField())

应该可以解决问题。

我不得不使用一些不同的东西来使我的查询工作。只是 output_field 不会解决它。我需要在两个别名之间进行简单划分。这些是两个注释的输出。

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()))

这里的关键是ExpressionWrapper。 没有这个,你会得到一个错误:received non-expression(s)

提示来自 Django 文档本身,它说:

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/