Zed
Zed

Reputation: 379

Issue with many to many relationships

I am not able to add one more player to this coach. Essentially a player can have many coaches, and a coach can have many players under him.

I tried to do a Many to Many relationships but then I was able to add the same player to the same coach twice.

What should I do here ?

class CoachPlayer(models.Model): coach = models.OneToOneField('Coach', on_delete=models.CASCADE) player = models.ForeignKey('player.Player', on_delete=models.CASCADE) start_date = models.DateTimeField(auto_now_add=True)

Upvotes: 0

Views: 30

Answers (1)

Nihal Sharma
Nihal Sharma

Reputation: 2437

Have a foreign reference to coach in the model.

Now a player cannot have multiple coaches so coach and player should be unique together. So make them unique. The model becomes:

class CoachPlayer(models.Model):
    coach = models.ForeignKey('Coach', on_delete=models.CASCADE)
    player = models.ForeignKey('player.Player', on_delete=models.CASCADE)
    start_date = models.DateTimeField(auto_now_add=True)

    class Meta:
       unique_together = ('coach', 'player')

Upvotes: 1

Related Questions