How to set up a junction table in Django

550 views
Skip to first unread message

Ben Gorman

unread,
Dec 17, 2014, 9:34:02 AM12/17/14
to django...@googlegroups.com

(I'm copying my question from Stack Overflow here because it didn't get any answers.  Please let me know if it's confusing.)

I'm trying to figure out the best way to model this data structure. I want to have a table of "Players" and and table of "Games" such that each game includes two or more players. E.g.

Players

PlayerID | PlayerName
1        | John
2        | Sue
3        | Bob

Games

GameID | GameDate
1      | 1/1/2014
2      | 2/1/2014

GamePlayers (junction table)

GamePlayerID | GameID | PlayerID 
1            | 1      | 1
2            | 1      | 2
3            | 1      | 3
4            | 2      | 2
5            | 2      | NULL

Notice the NULL value. This basically says "Game 2" consists of player 2 and one undetermined player. This functionality is what I need to replicate in Django. This is what I tried.

Models.py

class Player(models.Model):
    player_name = models.CharField(max_length=60)

class Game(models.Model):
    players = models.ManyToManyField(Player, blank=True)
    game_date = models.DateField(null=True, blank=True)

But with this setup I can't seem to replicate the functionality I described above. How do I accomplish this?

Tim Chase

unread,
Dec 17, 2014, 12:17:09 PM12/17/14
to django...@googlegroups.com, bgorm...@gmail.com
On 2014-12-17 06:34, Ben Gorman wrote:
> Notice the NULL value. This basically says "Game 2" consists of
> player 2 *and one undetermined* player. This functionality is what
> I need to replicate in Django. This is what I tried.
>
> Models.py
>
> class Player(models.Model):
> player_name = models.CharField(max_length=60)
> class Game(models.Model):
> players = models.ManyToManyField(Player, blank=True)
> game_date = models.DateField(null=True, blank=True)
>
> But with this setup I can't seem to replicate the functionality I
> described above. How do I accomplish this?

Sounds like you want to use the "through" property of a ManyToMany
field¹, something like

class Player(models.Model):
# ...

class Game(models.Model):
# ...
players = models.ManyToMany(Player, through="PlayerGame")

class PlayerGame(models.Model):
player = models.ForeignKey(Player)
game = models.ForeignKey(Game, blank=True, null=True)
# possible other attributes of a PlayerGame


-tkc

¹
https://docs.djangoproject.com/en/1.7/ref/models/fields/#django.db.models.ManyToManyField.through








.
Reply all
Reply to author
Forward
0 new messages