[Django]-Django – Model with 2 foreign keys from the same class

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.

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')

Leave a comment