'Database relationship between a match and its players

I'm trying to design a database that would save matches and players in a 3v3 game.

So far my models look like this :

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)

However the repetition of "player_<int>" is itching me, I don't think this is the proper way to do it. What if the number of player changes at some point, or how to I find if a player participated in a match ? I think it's a clunky approach at best.

How could I approach this better ? I was thinking about maybe a list of players, but I don't know how to characterize this kind of relationship.



Solution 1:[1]

You can use Django's ManyToManyField like the following.

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)

Then you can set players to a match.

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])

Hope it could help.

Solution 2:[2]

I think that what I was looking for was a ManyToMany Relationship. Doc : https://docs.djangoproject.com/fr/4.0/topics/db/examples/many_to_many/

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 David Lu
Solution 2 Benjamin_Mourgues