我有以下型号:-
class Group(models.Model):
name = models.CharField(max_length=200)
class Game(models.Model):
group = models.ForeignKey(Group, related_name='games')
date = models.DateField()
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')
selected = models.BooleanField(default=False)
injured = models.BooleanField(default=False)
class Player(models.Model):
group = models.ForeignKey('groups.Group', related_name='players')
user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='players')
我想用一个分数来注释组中的所有玩家:-
在最近10场没有受伤的比赛中,如果被选中,得分为5。
我可以使用Sum / Case / When忽略“没受伤”子句来执行此操作,方法是使用Player上的管理器方法,如下所示:-
def with_availability_scores(self, group):
for_games = group.games.reverse()[:10]
return self.annotate(
availability_score=Sum(Case(
When(
memberships__selected=True, memberships__game__in=for_games,
then=5)
default=0, output_field=IntegerField()))
)
但是添加了“ injured”子句意味着我不能像这样一开始就使用for_games变量。
我怀疑可以使用Subquery和OuterRef来完成,但我不太清楚我需要的确切语法。
有什么想法吗?