我正在开发的游戏应用程序中有以下模型:-
class Player(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='players')
class Game(models.Model):
players = models.ManyToManyField(Player, through='GameMembership', related_name='games')
class GameMembership(models.Model):
game = models.ForeignKey(Game, related_name='memberships')
player = models.ForeignKey(Player, related_name='memberships')
team = models.ForeignKey(Team, null=True, related_name='memberships')
selected = models.BooleanField(default=False)
class Team(models.Model):
game = models.ForeignKey(Game, related_name='teams')
score = models.IntegerField(null=True)
我想获取所有玩家的列表以及他们被选中的次数,所以我这样注释查询集:-
Player.objects.all().annotate(played=Count(Case(When(memberships__selected=True, then=1))))
完全按预期工作。
但是,我还想要每个球员被选中的所有比赛中的总进球数,所以我这样注释:-
Player.objects.all().annotate(played=Count(Case(When(memberships__selected=True, then=1))), total_goals=Sum(Case(When(memberships__selected=True, then='games__teams__score'))))
这为 total_goals 提供了正确的数字,但由于某种原因,播放次数的值翻了一番!
我所做的就是添加这个注释: -
total_goals=Sum(Case(When(memberships__selected=True, then='games__teams__score')))
所以发生了什么事?我强烈怀疑我需要在某处进行 distinct() 调用,但我不明白为什么额外的注释会对第一个注释产生影响。
有任何想法吗?