amir_70
amir_70

Reputation: 930

how to add two fields as foreign key to a table?

I have two tables "team" and "match". every team can be on different matches and every match contain two or more teams and so it's a manytomany relation. here is my match model:

class Match(models.Model):
    result = models.CharField(max_length=10, default='')
    winner = models.??????
    team = models.ManyToManyField(Team, related_name='team')
    referee = models.ForeignKey(User, on_delete=models.PROTECT, 
        related_name='referee')

the winner of every match is also a team but I don't know how to handle it. should I define it as foreign-key to team table? what is the right way?

Upvotes: 0

Views: 58

Answers (2)

ybl
ybl

Reputation: 1605

The related_name argument specifies the back relation from your intermediate table, use:

winner = models.ForeignKey(Team, related_name='winning_team')

Edit: Nico actually named the related_name logically better, as one would access the matches_won from the team object.

Upvotes: 2

Nico Griffioen
Nico Griffioen

Reputation: 5405

Use a ForeignKey:

winner = models.ForeignKey(Team, related_name='matches_won')

Upvotes: 3

Related Questions