比赛与其球员之间的数据库关系

Database relationship between a match and its players

我正在尝试设计一个数据库来保存 3v3 游戏中的比赛和玩家。

到目前为止,我的模型是这样的:

class Player(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE, null=True)
    player_tag = models.CharField(max_length=9, unique=True)
    player_name = models.CharField(max_length=50)
    trophy_count = models.IntegerField(default=0)
    club = models.ForeignKey('Club', on_delete=models.SET_NULL, null=True)
    total_club_war_trophy_count = models.IntegerField(default=0)


class Club(models.Model):
    club_name = models.CharField(max_length=50)
    club_tag = models.CharField(max_length=9, unique=True)


class Match(models.Model):
    # Matches are 3v3
    player_1 = models.ForeignKey(Player, on_delete=models.CASCADE)
    player_2 = models.ForeignKey(Player, on_delete=models.CASCADE)
    player_3 = models.ForeignKey(Player, on_delete=models.CASCADE)
    player_4 = models.ForeignKey(Player, on_delete=models.CASCADE)
    player_5 = models.ForeignKey(Player, on_delete=models.CASCADE)
    player_6 = models.ForeignKey(Player, on_delete=models.CASCADE)
    # Brawlball, Gem grab, Knockout ...
    mode = models.CharField(max_length=20)
    # Power match or normal match
    battle_type = models.CharField(max_length=20)
    trophies_won = models.IntegerField(default=0)
    date = models.DateTimeField(auto_now_add=True)

但是“player_<int>”的重复让我很痒,我认为这不是正确的做法。如果玩家数量在某个时候发生变化怎么办,或者我如何找到玩家是否参加了比赛?我认为这充其量是一种笨拙的方法。

我怎样才能更好地解决这个问题?我在想也许是一个球员名单,但我不知道如何描述这种关系。

我认为我正在寻找的是多对多关系。 文件:https://docs.djangoproject.com/fr/4.0/topics/db/examples/many_to_many/

您可以像下面这样使用 Django 的 ManyToManyField

class Match(models.Model):
    # Matches are 3v3
    players = models.ManyToManyField(Player, blank = True)
    # Brawlball, Gem grab, Knockout ...
    mode = models.CharField(max_length=20)
    # Power match or normal match
    battle_type = models.CharField(max_length=20)
    trophies_won = models.IntegerField(default=0)
    date = models.DateTimeField(auto_now_add=True)

然后你可以设置玩家匹配。

match = Match.objects.get(pk = 1)
# players with ids (1,2,3) are in the match with id of 1.
match.players.set([1,2,3])

希望对您有所帮助。