2017-08-10 49 views
0

A有兩個包含數據的模型表。如何將已有字段設置爲另一個表的外鍵?

class A(models.Model): 
    id = models.PositiveIntegerField(primary_key=True) 
    #some other fields 
    other_id = models.IntegerField(default=0, null=True) 

而第二類

class B(models.Model): 
    id = models.PositiveIntegerField(primary_key=True) 
    #some other fields 

現在我想實地A.other_id成爲相關field B.id一個ForeignKey。 我無法使用SQL。我知道它應該是這樣的:

b = models.ForeignKey(B, db_column="other_id") 

但它似乎不起作用。

+0

我認爲你需要把你真實的代碼,你嘗試錯誤,你有更多的細節==>更快,更正確的答案 –

回答

0

您試過to_field選項嗎?

你可以這樣做:

b = models.ForeignKey(B, to_field="other_id") 

然而,美中不足的是,現場other_id必須滿足unique=True

相關問題