我有 2 个 Django 模型(表)玩家和游戏,具有多对多关系,第三个作为它们之间的中间表,其中玩家用户名作为外键(用户名是玩家的表主键),一个 game_id FK ,以及额外的属性分数。
2人以上可以玩同一游戏。
如何让每个游戏都由两个玩家玩?
class Player(models.Model):
username = models.CharField(max_length=20, primary_key=True)
fname = models.CharField(max_length=20, blank=False)
lname = models.CharField(max_length=20, blank=False)
avatar = models.ImageField(upload_to='./app/avatars/', blank=True, null=True)
is_online = models.BooleanField(default=False)
game_theme = models.ImageField(upload_to='./app/themes/', blank=True, null=True)
played_games_num = models.IntegerField(default=0)
def __str__(self):
return self.username
class Game(models.Model):
mode_choices = {
'classic': 'Classic',
'vs_robot': 'Vs Robot'
}
difficulty_choices = {
-1: 'Vs Player',
1: 'Easy',
2: 'Medium',
3: 'Hard'
}
game_id = models.AutoField(primary_key=True)
mode = models.CharField(max_length=10, choices=mode_choices)
difficulty = models.IntegerField(choices=difficulty_choices)
game_date_time = models.DateTimeField(auto_now_add=True)
duration = models.IntegerField()
players = models.ManyToManyField(Player, through='Player_game')
def __str__(self):
return str(self.game_id)
class Player_game(models.Model):
username = models.ForeignKey(Player, on_delete=models.CASCADE)
game = models.ForeignKey(Game, on_delete=models.CASCADE)
score = models.IntegerField()
class Meta:
unique_together = ['username', 'game']
def __str__(self):
return str(self.game_id)
在 Meta 类中添加 unique_together 并没有解决问题。