我期待用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')
這樣寫,django會(huì)自動(dòng)關(guān)聯(lián)到Persons表的主鍵,而非我期待的Id_P
請(qǐng)教一下,要如何改寫,才能實(shí)現(xiàn)我的預(yù)期效果?
人生最曼妙的風(fēng)景,竟是內(nèi)心的淡定與從容!
看來(lái)db_column參數(shù)不能指定使用哪個(gè)字段作外鍵(估計(jì)樓主使用過(guò)sqlalchemy),
查看下django ForeignKey 文檔有這個(gè)參數(shù)
ForeignKey.to_field
The 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就行了