python - Django model foreignKey Reference
問(wèn)題描述
我期待用django創(chuàng)建數(shù)據(jù)庫(kù)的時(shí)候?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’)
這樣寫(xiě),django會(huì)自動(dòng)關(guān)聯(lián)到Persons表的主鍵,而非我期待的Id_P
請(qǐng)教一下,要如何改寫(xiě),才能實(shí)現(xiàn)我的預(yù)期效果?
問(wèn)題解答
回答1:看來(lái)db_column參數(shù)不能指定使用哪個(gè)字段作外鍵(估計(jì)樓主使用過(guò)sqlalchemy),
查看下django ForeignKey 文檔有這個(gè)參數(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. docker-compose中volumes的問(wèn)題2. 關(guān)docker hub上有些鏡像的tag被標(biāo)記““This image has vulnerabilities””3. boot2docker無(wú)法啟動(dòng)4. docker網(wǎng)絡(luò)端口映射,沒(méi)有方便點(diǎn)的操作方法么?5. docker安裝后出現(xiàn)Cannot connect to the Docker daemon.6. javascript - mock.js可以存儲(chǔ)數(shù)據(jù)嗎7. java - SSH框架中寫(xiě)分頁(yè)時(shí)service層中不能注入分頁(yè)類8. nignx - docker內(nèi)nginx 80端口被占用9. 求救一下,用新版的phpstudy,數(shù)據(jù)庫(kù)過(guò)段時(shí)間會(huì)消失是什么情況?10. mac里的docker如何命令行開(kāi)啟呢?

網(wǎng)公網(wǎng)安備