我在游戏应用程序中有以下模型: -
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')))
那发生了什么?我强烈怀疑我需要在某个地方进行明确的()调用,但我不明白为什么额外的注释会对第一个注释产生影响。
有什么想法吗?