Reputation: 242
I am using Django as a game server, and need to group players. My group can contain up to n players, each assigned a player number (player1, player2, etc). How can I store players and record their player number?
One obvious option is the following:
class Group(models.Model):
player1 = models.ForeignKey(Player)
player2 = models.ForeignKey(Player)
player3 = models.ForeignKey(Player)
playerN = models.ForeignKey(Player)
However, this makes it really difficult to iterate through the list of players. I would like to store them in a structured list somehow but cannot think of how to do this.
Any thoughts would be greatly appreciated.
Upvotes: 0
Views: 45
Reputation: 774
You're looking for a way to create arbitrary mappings between users and groups, a many-to-many relationship. From a database schema perspective, you're looking for a junction table.
Django gives you a way to create these sorts of relationships using models.ManyToManyField. But you don't necessarily have to use that field if you don't want to, it's straightforward enough to create your own junction table as its own model in manual fashion with foreign keys out to your group and player classes. ManyToManyField even lets you specify the junction table as your custom model class using the through
keyword argument.
It's through a custom junction table that you can not only store the player in a group and which group the player is in, but also the player number:
class Player(models.Model)
...
class Group(models.Model)
...
players = models.ManyToManyField(Player, through=PlayerGroupJunction)
class PlayerGroupJunction(models.Model)
player = models.ForeignKey(Player)
group = models.ForeignKey(Group)
number = models.IntegerField()
Upvotes: 1
Reputation: 442
If player can be part of multiple groups then you should use many to many relation
class Player(models.Model):
name = models.TextField()
number = models.IntegerField()
class Group(models.Model):
name = models.TextField()
players = models.ManyToManyField(Player)
then you add players by group.players.add(player)
more info here
If you need to store more than just relation (for example player may have different number in each group) then you have to create M2M table by yourself
class Player(models.Model):
name = models.TextField()
class Group(models.Model):
name = models.TextField()
class PlayerToGroup(models.Model):
player = models.ForeignKey(Player)
group = models.ForeignKey(Group)
number = models.IntegerField()
Upvotes: 1