Django - a model with two foreign keys of the same class

I need a Django model with two foreign keys from the same table. This is an event table that has 2 columns for employees: “home” and “away”. But I get this error: Error: one or more models did not check ...

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. Thank!

+3
source share
2 answers

Change the model Matchto 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 something to say about related_name:

The name to be used for the relationship from the associated object to this.

, Team , , . Match. Team, team.match_set. related_name FK, .

@Török Gábor , team.home_set team.away_set .

+6

. match_set Team. Team , , related_name ForeignKey s.

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

Source: https://habr.com/ru/post/1765304/


All Articles