python - Django model foreignKey Reference
問題描述
我期待用django創(chuàng)建數(shù)據(jù)庫的時候?qū)崿F(xiàn)以下效果
表1
CREATE TABLE Persons(Id_P int NOT NULL,LastName varchar(255) NOT NULL,FirstName varchar(255),Address varchar(255),City varchar(255),UNIQUE (Id_P),PRIMARY KEY (LastName))
表2
CREATE TABLE Orders(Id_O int NOT NULL,OrderNo int NOT NULL,Id_P int,PRIMARY KEY (Id_O),FOREIGN KEY (Id_P) REFERENCES Persons(Id_P))
表2的外鍵關(guān)聯(lián)到表一的Id_P,而不是LastName
但在django中
Id_P = models.ForeignKey(’Persons’,db_column=’Id_P’)
這樣寫,django會自動關(guān)聯(lián)到Persons表的主鍵,而非我期待的Id_P
請教一下,要如何改寫,才能實現(xiàn)我的預(yù)期效果?
問題解答
回答1:看來db_column參數(shù)不能指定使用哪個字段作外鍵(估計樓主使用過sqlalchemy),
查看下django ForeignKey 文檔有這個參數(shù)
ForeignKey.to_fieldThe field on the related object that the relation is to. By default, Django uses the primary key of the related object. If you reference a different field, that field must have unique=True.
所以改db_column為to_field就行了
相關(guān)文章:
1. 數(shù)組按鍵值封裝!2. docker不顯示端口映射呢?3. java - 阿里的開發(fā)手冊中為什么禁用map來作為查詢的接受類?4. javascript - 使用vue官方腳手架進行單元測試,如何覆蓋到watch里的變量?5. javascript - 為什么創(chuàng)建多行多列的表格最后只有一行內(nèi)有表格6. 如何用Java向kafka發(fā)送json數(shù)據(jù)7. javascript - webpack中alias配置中的“@”是什么意思?8. clone - git sourceTree克隆倉庫時,都不停彈出Password Required彈窗,即時輸入正確的git賬號密碼還是彈出9. 主題切換問題,用過別人的webapp在后臺切換模板主題后手機端打開網(wǎng)頁就是切換到的主題了10. html5 - 使用echarts中的圖表 一個頁面導(dǎo)入了好幾個js圖表 實現(xiàn)echarts圖表隨著瀏覽器窗口變化而變化時出現(xiàn)了問題
