python - Django model foreignKey Reference
問題描述
我期待用django創建數據庫的時候實現以下效果
表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的外鍵關聯到表一的Id_P,而不是LastName
但在django中
Id_P = models.ForeignKey(’Persons’,db_column=’Id_P’)
這樣寫,django會自動關聯到Persons表的主鍵,而非我期待的Id_P
請教一下,要如何改寫,才能實現我的預期效果?
問題解答
回答1:看來db_column參數不能指定使用哪個字段作外鍵(估計樓主使用過sqlalchemy),
查看下django ForeignKey 文檔有這個參數
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就行了
相關文章:
1. 怎么在phpstudy中用phpexcel上傳數據到MYSQL?2. javascript - 百度搜索網站,如何讓搜索結果顯示一張圖片加上一段描述,如圖;求教3. phpadmin的數據庫,可以設置自動變化時間的變量嗎?就是不需要接收時間數據,自動變化4. html5和Flash對抗是什么情況?5. 求救一下,用新版的phpstudy,數據庫過段時間會消失是什么情況?6. html - 爬蟲時出現“DNS lookup failed”,打開網頁卻沒問題,這是什么情況?7. mac里的docker如何命令行開啟呢?8. boot2docker無法啟動9. 這是什么情況???10. gosts內容是空的
