有这样的模型关系
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()
.
所以我有点迷路了。我试着用原始sql进行注释,但在这种情况下,我似乎无法引用
risk.id
这对于为每个风险获得正确的组名非常重要。