views:

46

answers:

2

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!

+3  A: 

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.

Manoj Govindan
+3  A: 

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')
Török Gábor
@Matthew Rankin: it was my mistake, sorry, but corrected it already as I realized.
Török Gábor