Lorenzo Fiamingo
Lorenzo Fiamingo

Reputation: 4109

Relationship field in Django

I have the following structure in my models.py document:

class Player(Human):
    name = models.CharField(max_lenght=24)
    jersey_number = models.IntegerField()

class Coach(Human):
    name = models.CharField(max_lenght=24)

class Team(models.Model):
    name = models.CharField(max_length=24)
    players = models.SomethinToSomething(Player)
    coaches = models.SomethinToSomething(Coach)

I would like in my admin section to create teams and inside each team add some players and some coaches, I want that a player is related only with the team where I created it, so if I'm in team A it has to be impossible for me see and adding player of other team.

I tried OneToOne() but I can link only one player and only one coach to the team. I tried ManyToMany() but when I make the second team the players of the first team are shared with the first team.

What should I use?

Upvotes: 1

Views: 425

Answers (2)

Bidhan Majhi
Bidhan Majhi

Reputation: 1370

I suggest you do something like this,

class Team(models.Model):
      name = # ..

class Player(models.Model):
      name = # ..
      jer_num = # ...
      team = models.ForeignKey(Team, #..)

class Coach(models.Model):
     name = # ..
     team = models.ForeignKey(Team, #..)

When you will add a player or a coach, the team will be added as a choice field. Because, the the teams (mostly) remain same and the players and coaches changes, this will give you flexibility. And also if you want to add something like transfer, you can use team in your forms.

Upvotes: 3

shafikshaon
shafikshaon

Reputation: 6404

Simply use ForeignKey() to achieve your desired.

Upvotes: 0

Related Questions