Django:GROUP BY两个值

z5btuh9x  于 2023-08-08  发布在  Go
关注(0)|答案(2)|浏览(113)

我基本上想做the same as this question,但通过两个值的组合进行分组,而不仅仅是一个:

SELECT player_type, team, COUNT(*)
FROM players
GROUP BY player_type, team;

字符串
有谁知道这在Django中是否可能,以及如何实现?我用1.2

wko9yo5t

wko9yo5t1#

(Player.objects
 .values('player_type', 'team')
 .order_by()
 .annotate(Count('player_type'), Count('team'))

字符串

snz8szmq

snz8szmq2#

最直接的方法是计算对象的id字段,并触发values()annotate()进行分组。
假设OP的原始查询,使用Django(v4.2)数据模型,如下所示:

# home/models.py
class Player(models.Model):
    player_type = models.CharField(max_length=50)
    team = models.CharField(max_length=50)

字符串
执行:

Player.objects.values('player_type', 'team').annotate(Count('id'))


将产生所需的输出,计数在新字段id__count中。
最好对QuerySet上的.query属性进行安全检查。在上一个示例中,生成了类似于以下内容的内容:

-- print(Player.objects.values('player_type', 'team').annotate(Count('id')).query)

SELECT "home_player"."player_type"
     , "home_player"."team"
     , COUNT("home_player"."id") AS "id__count"
FROM "home_player"
GROUP BY "home_player"."player_type", "home_player"."team"

相关问题