Cometchaser
Cometchaser

Reputation: 137

How to model a one to many relationship in Django

in my current Django project I have list of players and a list of games and I'm looking for a Django field to store the information in which games the player participate. To give an example: User 1 played Game 1, 2, 3, and User 2 played 2, 3... Since not all players of a game are registered, I'm not looking for the relation game to player. So, I'm looking for something like an one-to-may field (player to several games).

So far, I found the ForeignKey field. However, when I add this to game, I can only store one player not several player ids. Or do I missed something?

How do I express my problem in Django model fields?

Upvotes: 0

Views: 96

Answers (1)

Sergey Pugach
Sergey Pugach

Reputation: 5669

As far as One user can participate in different games and one Game can contain several users you may need ManyToMany relation. You can add users as a ManyToMany field to Game model:

users = models.ManyToManyField('User')

in order to add user to a game you can do:

game = Game.objects.get(...)
user1 = User.objects.get(...)
user2 = User.objects.get(...)
users = [user1, user2]
game.users.add(*users)

If you want to see all users of particular game:

game = Game.objects.get(...)
game.users.all()

If you want to see which games a particular user participated:

user = User.objects.get(...)
user.game_set.all()

Upvotes: 1

Related Questions