【问题标题】:GROUP BY in Django ORM with aggregation带有聚合的 Django ORM 中的 GROUP BY
【发布时间】:2014-09-05 00:16:13
【问题描述】:

我需要实现这样的查询:

Table1
|Id | Name   |
| 1 | Peter  |
| 2 | Andrew |

Table2
| Score | Table1Id |
| 10    | 1        |
| 20    | 1        |
| 100   | 1        |
| 0     | 2        |
| 30    | 2        |

我需要选择所有名称 {name, min_score, max_score}

{Peter, 10, 100}
{Andrew, 0, 30}

类似:

SELECT DISTINCT MIN(score), MAX(score) Table1.name FROM Table1, Table2 WHERE Table1.Id = Table2.Table1Id GROUP BY Table1.Name

在 ORM 中类似于:

Table2.objects.all().annotate(min_score=Min('score'), max_score=Max('score')).values('Table1.Name!!!!', 'min_score', 'max_score')

【问题讨论】:

  • 你应该发布模型定义 - 你有一个从 Table2 到 Table1 的外键?

标签: sql django django-orm


【解决方案1】:

试试这个:

Table2.objects.values('table1__name').annotate(min_score=Min('score'), max_score=Max('score'))

带注释的字段将被添加到结果中,它们不需要进入values(...),但是您在values(...) 中输入的任何内容都将用作GROUP BY 字段

【讨论】:

    猜你喜欢
    • 2017-06-10
    • 2017-08-17
    • 2021-08-01
    • 2019-02-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-26
    相关资源
    最近更新 更多