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. 在mac下出現了兩個docker環境2. css3 - css怎么實現圖片環繞的效果3. android - 用textview顯示html時如何寫imagegetter獲取網絡圖片4. javascript - 原生canvas中如何獲取到觸摸事件的canvas內坐標?5. css - 定位為absolute的父元素中的子元素 如何設置在父元素的下面?6. JavaScript事件7. javascript - jquery hide()方法無效8. 網頁爬蟲 - 用Python3的requests庫模擬登陸Bilibili總是提示驗證碼錯誤怎么辦?9. 注冊賬戶文字不能左右分離10. html - vue項目中用到了elementUI問題
