Django 1.11批注GROUP BY错误

时间:2018-12-07 11:27:40

标签: django group-by subquery

具有这样的模型关系

Risk <-- RiskGroup --> Group

我正在尝试实现与此类似的查询

SELECT risk.id,
       (
         SELECT array_agg(bg.name) as names
         FROM hazards_riskgroup rgroup
                JOIN (SELECT * FROM base_group ORDER BY name) as bg
                     on rgroup.group_id = bg.id
         WHERE risk_id = risk.id
         GROUP BY risk_id
         ORDER BY risk_id
       ) AS conf
FROM hazards_risk risk
ORDER BY conf NULLS LAST
;

我已经达到

group_names = (
    RiskGroup.objects
    .filter(risk_id=OuterRef('pk'))
    .annotate(names=ArrayAgg('group__name'))
    .order_by()
    .order_by("group__name")
    .values('names')
)
qs = Risk.objects.annotate(
    conf=Subquery(group_names)
).order_by(F('conf').asc(nulls_last=True))

但这会在查询中产生一些东西

SELECT risk.id,
       (SELECT ARRAY_AGG(U2."name") AS "names"
        FROM "hazards_riskgroup" U0
               INNER JOIN "base_group" U2 ON (U0."group_id" = U2."id")
        WHERE U0."risk_id" = (risk.id)
        GROUP BY U0."id", U2."name"
        ORDER BY U2."name" ASC) AS "conf"
FROM hazards_risk risk
ORDER BY conf NULLS LAST

请注意,生成的GROUP BY变成了GROUP BY U0."id", U2."name",我只想在这里GROUP BY U2."name"

据我所知,它与模型上的某些默认排序有关,但是正如您所知道的,我已经通过插入.order_by()来解决这个问题。

所以我有点迷路了。我尝试使用Raw sql进行注释,但是在那种情况下,我似乎无法引用risk.id,这对于获取每种风险的正确组名很重要。

0 个答案:

没有答案