anhtran
anhtran

Reputation: 2034

Django - Model with 2 foreign keys from the same class

I wanted a Django model with 2 foreign keys from the same table. It's an event table which has 2 columns for employees: the 'home' and the 'away'. But I get this error: Error: One or more models did not validate...

class Team(models.Model):
    name = models.CharField(max_length=200)

class Match(models.Model):
    home = models.ForeignKey(Team)
    away = models.ForeignKey(Team)

Any idea for this. Thanks!

Upvotes: 3

Views: 4123

Answers (2)

Manoj Govindan
Manoj Govindan

Reputation: 74675

Change the Match model to use related_name.

class Match(models.Model):
    home = models.ForeignKey(Team, related_name="home_set")
    away = models.ForeignKey(Team, related_name="away_set")

The documentation has this to say about related_name:

The name to use for the relation from the related object back to this one.

You are getting the error because from the Team side there will be two relations and they will both have the name, viz. match. You'll refer to this from the Team side using team.match_set. By changing the related_name of the second FK you are fixing this.

Update

As @Török Gábor said, you can now use team.home_set and team.away_set respectively.

Upvotes: 6

viam0Zah
viam0Zah

Reputation: 26312

Django follows relationship backwards, too. By default, it creates attribute match_set on your Team objects. Because you referenced Team twice, you must distinguish those backwards attributes by providing related_name attribute on ForeignKeys.

class Match(models.Model):
    home = models.ForeignKey(Team, related_name='home_set')
    away = models.ForeignKey(Team, related_name='away_set')

Upvotes: 7

Related Questions