Django ORM中的GROUP BY与聚合

时间:2014-07-14 23:00:45

标签: sql django django-orm

我需要实现这样的查询:

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')

1 个答案:

答案 0 :(得分:0)

试试这个:

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

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