2010-09-17 111 views
3

我想要一个带有来自同一个表的两个外键的Django模型。这是一个事件表,其中有两列员工:'家'和'走'。但我得到这个错误:错误:一个或多个模型没有验证...Django - 带有来自同一类的两个外键的模型

class Team(models.Model): 
    name = models.CharField(max_length=200) 

class Match(models.Model): 
    home = models.ForeignKey(Team) 
    away = models.ForeignKey(Team) 

对此的任何想法。谢谢!

+0

您可以引用整个错误信息以供将来参考。 – 2010-09-17 15:32:33

+1

[我怎样才能在Django中有两个外键给同一个模型?](http://stackoverflow.com/questions/543377/how-can-i-have-two-foreign-keys-to-the - 同名模型在Django) – 2010-09-17 18:45:52

+0

可能重复[我怎么能有两个外键在Django的同一模型?](https://stackoverflow.com/questions/543377/how-can-i-have-两个外键的django模型 – 2017-08-14 14:31:35

回答

6

Match型号更改为使用related_name

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

的文档具有这样说related_name

The name to use for the relation from the related object back to this one.

你所得到的错误,因为从Team侧会有两个关系,他们都将有名字,即。 match。您将使用team.match_setTeam一侧引用此内容。通过更改第二个FK的related_name您正在解决这个问题。

更新

正如@Török的Gabor said,你现在可以使用分别与team.home_setteam.away_set

6

Django也跟着关系向后。默认情况下,它会在您的Team对象上创建属性match_set。由于您引用了Team两次,因此您必须在ForeignKey上提供related_name attribute来区分这些向后属性。

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

@马修兰金:这是我的错误,对不起,但已纠正它,因为我意识到。 – 2010-09-17 15:31:41

相关问题