SQL FROM 部分中的 Django 子查询

问题描述

The Django Documentation 展示了如何在 SQL 查询的 SELECT 部分创建子查询,但是如何在 FROM 部分创建子查询呢?即:

SELECT    ...
FROM (
    SELECT    ...
    FROM      ...
    WHERE     ...
    GROUP BY  ...
)
WHERE     ...
ORDER BY  ...

这里有一个具体的例子,以防万一,但如果你能在没有这个例子的情况下回答上面的一般问题,请这样做。


如果我们有模型:

class MyModel(models.Model):
    field1 = models.CharField()
    other_model = models.ForeignKey(OtherModel)


class OtherModel(models.Model):
    field2 = models.CharField()
    field3 = models.CharField()
    active = models.BooleanField()

假设我想为每个 my_model.field1 值计算 OtherModel.field3 值的数量,其中有一些实例 my_model,other_modelmy_model.other_model == other_model and other_model.active == True 所以我想有一个子查询,我按 field1field3 分组并计算 active

sub_query = MyModels.values('field1','othermodel__field3').annotate(actives=Count(Case(When(othermodel__active=True,then=1))))

然后是一个主查询,我将第一个查询的结果按 field1 分组并按组计算它们:

main_query = qub_query.values('field1').annotate(active_combinations=Count('field1',filter=Q(actives__gt=0)))

但这是以不同的方式解释的,不能像这样工作。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)