2010-09-17 108 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

相關問題