开发者

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: Err开发者_如何转开发or: 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!


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜