FK的FK注释计数

时间:2019-06-14 05:12:15

标签: django django-models django-queryset

我有一个“团队”课程,一个“游戏”课程,一个“玩家”课程和一个“目标”课程。

考虑到我具有以下结构,如何注释每个“团队”的“目标”计数:

class Team(models.Model):
    name = models.CharField('Team name', max_length=255)

class Game(models.Model):
    team1 = models.ForeignKey(Team, verbose_name = 'Team 1')
    team2 = models.ForeignKey(Team, verbose_name = 'Team 2')

class Player(models.Model):
    team = models.ForeignKey(Team, verbose_name = 'Team')

class Goal(models.Model):
    player = models.ForeignKey(Player, verbose_name = 'Player')
    game = models.ForeignKey(Game, verbose_name = 'Game')

到目前为止,我已经尝试过:

Team.objects.annotate(nr_goals=Count('goal')).order_by('nr_goals')

如果需要,我还可以更改我的模型。

1 个答案:

答案 0 :(得分:2)

您已经在正确的道路上。试试:

Team.objects.annotate(nr_goals=Count('game__goal')).order_by('nr_goals')

您还可以使用Player模型关系。

Team.objects.annotate(nr_goals=Count('player__goal')).order_by('nr_goals')