您无法进行汇总的汇总
Max(Sum()),无论您是否使用ORM,它在SQL中都是无效的。相反,您必须将表自身联接起来才能找到最大值。您可以使用子查询来执行此操作。下面的代码对我来说似乎很正确,但是请记住,我没有什么可以运行的,因此它可能并不完美。
from django.db.models import Subquery, OuterRefannotation = { 'AcSum': Sum('intensity')}# The basic query is on Relation grouped by A and Category, annotated# with the Sum of intensityquery = Relation.objects.values('a', 'b__category').annotate(**annotation)# The subquery is joined to the outerquery on the Categorysub_filter = Q(b__category=OuterRef('b__category'))# The subquery is grouped by A and Category and annotated with the Sum# of intensity, which is then ordered descending so that when a LIMIT 1# is applied, you get the Max.subquery = Relation.objects.filter(sub_filter).values('a', 'b__category').annotate(**annotation).order_by('-AcSum').values('AcSum')[:1]query = query.annotate(max_intensity=Subquery(subquery))这应该生成如下的SQL:
SELECt a_id, category_id, (SELECT SUM(U0.intensity) AS AcSum FROM RELATION U0 JOIN B U1 on U0.b_id = U1.id WHERe U1.category_id = B.category_id GROUP BY U0.a_id, U1.category_id ORDER BY SUM(U0.intensity) DESC LIMIT 1 ) AS max_intensityFROM RelationJOIN B on Relation.b_id = B.idGROUP BY Relation.a_id, B.category_id
通过使用特定于后端的功能(例如array_agg(Postgres)或GroupConcat(MySQL))收集在外部查询中分组在一起的Relation.id,在子查询中消除联接可能会更有效。但是我不知道您正在使用什么后端。



