3

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!

anhtran
  • 2,006
  • 4
  • 27
  • 53
  • You may quote the whole error message for future reference. – viam0Zah Sep 17 '10 at 15:32
  • 1
    possible duplicate of [How can I have two foreign keys to the same model in Django?](http://stackoverflow.com/questions/543377/how-can-i-have-two-foreign-keys-to-the-same-model-in-django) – viam0Zah Sep 17 '10 at 18:45
  • Possible duplicate of [How can I have two foreign keys to the same model in Django?](https://stackoverflow.com/questions/543377/how-can-i-have-two-foreign-keys-to-the-same-model-in-django) – Aaron McMillin Aug 14 '17 at 14:31

2 Answers2

7

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')
viam0Zah
  • 25,949
  • 8
  • 77
  • 100
6

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.

Community
  • 1
  • 1
Manoj Govindan
  • 72,339
  • 21
  • 134
  • 141