首页 > 解决方案 > Django 从子查询中选择

问题描述

我想使用窗口函数进行查询,然后通过对子查询的聚合进行一些分组。但我无法使用 ORM 方法。它会回来aggregate function calls cannot contain window function calls

有什么方法可以在不使用的情况下进行如下 SQL 的查询.raw()

SELECT a.col_id, AVG(a.max_count) FROM (
  SELECT col_id,
  MAX(count) OVER (PARTITION BY part_id ORDER BY part_id) AS max_count
  FROM table_one
) a
GROUP BY a.col_id;

例子

table_one

| id | col_id | part_id | count |
| -- | ------ | ------- | ----- |
| 1  | c1     | p1      | 3     |
| 2  | c2     | p1      | 2     |
| 3  | c3     | p2      | 1     |
| 4  | c2     | p2      | 4     |

首先,我想获得基于 part_id 的最大基数

| id | col_id | part_id | count | max_count |
| -- | ------ | ------- | ----- | --------- |
| 1  | c1     | p1      | 3     | 3         |
| 2  | c2     | p1      | 2     | 3         |
| 3  | c3     | p2      | 1     | 4         |
| 4  | c2     | p2      | 4     | 4         |

最后通过 col_id 得到 max_count 组的平均值

| col_id | avg(max_count) |
| ------ | -------------- |
| c1     | 3              |
| c2     | 3.5            |
| c3     | 4              |

我现在拥有的模型

def Part(models.Model):
    part_id = models.UUIDField(primary_key=True, editable=False, default=uuid.uuid4)
    name = models.CharFields()

def Col(models.Model):
    part_id = models.UUIDField(primary_key=True, editable=False, default=uuid.uuid4)
    name = models.CharFields()

def TableOne(models.Model):
    id = models.UUIDField(primary_key=True, editable=False, default=uuid.uuid4)
    col_id = models.ForeignKey(
        Col,
        on_delete=models.CASCADE,
        related_name='table_one_col'
    )
    part_id = models.ForeignKey(
        Part,
        on_delete=models.CASCADE,
        related_name='table_one_part'
    )
    count = models.IntegerField()

我想在分区后进行分组。这是我所做的查询,它会带来错误。

query = TableOne.objects.annotate(
    max_count=Window(
        expression=Max('count'),
        order_by=F('part_id').asc(),
        partition_by=F('part_id')
    )
).values(
    'col_id'
).annotate(
    avg=Avg('max_count')
)

标签: pythonpython-3.xdjangodjango-modelsdjango-rest-framework

解决方案


您可以在 Django 中使用子查询,不需要使用窗口函数。首先,子查询是一个查询Part集,用最大计数注释TableOne

from django.db.models import Avg, Max, Subquery, OuterRef

parts = Part.objects.filter(
    id=OuterRef('part_id')
).annotate(
    max=Max('table_one_part__count')
)

然后TableOne用子查询中的最大计数注释查询集,values在我们想要分组的列上执行 ( col_id ),然后再次用平均值注释以生成所需的输出

TableOne.objects.annotate(
    max_count=Subquery(parts.values('max')[:1])
).values(
    'col_id'
).annotate(
    Avg('max_count')
)

推荐阅读