Django模型选择播放器

时间:2019-07-07 19:59:14

标签: django django-models

我有MatchGame牌桌,我想选择要参加这场比赛的球员(因为一支球队中有5名以上的球员,但是一场比赛的比分是5vs5)

class Match(models.Model):
name=models.CharField(max_length=255)
slug=models.SlugField(unique=True,max_length=255)
team1=models.ForeignKey('Team',related_name='team1',on_delete=models.PROTECT)
team2=models.ForeignKey('Team',related_name='team2',on_delete=models.PROTECT)

class Game(models.Model):
name = models.CharField(max_length=255)
match = models.ForeignKey(Match, on_delete=models.CASCADE)
team1players=models.ManyToManyField(match.team1.player.all())
team2players=models.ManyToManyField(match.team1.player.all())

错误:'ForeignKey' object has no attribute 'team1'

1 个答案:

答案 0 :(得分:0)

您可以在team1players模型中动态添加一个名为team2players之类的ForeignKey字段,而不是在Game模型中包含current_gamePlayer将当前Game对象分配给团队中的每5个玩家。这是一个示例:

# models.py, Player model
class Player(models.Model):
    name = models.CharField(max_length=255)
    team = models.ForeignKey(Team)
    # ... other fields ...
    current_game = models.ForeignKey(Game, blank=True, null=True, related_name='current_players')

# ------------------------------------------------

# views.py
game = Game(name='Sample game')
# some operations
player1.current_game = game
player1.save()
game.save()

# You can access for current players in the game in team order like:
current_players_in_game = game.current_players.values('team', 'name').order_by('team')