python - Django model foreignKey Reference
黄舟
黄舟 2017-05-18 10:46:04
0
1
472

I expect to achieve the following effects when using django to create a database

Table 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)
)

Table 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)
)

The foreign key of table 2 is related to the Id_P of table 1, not LastName

But in django

Id_P = models.ForeignKey('Persons',db_column='Id_P')

Written like this, django will automatically associate it with the primary key of the Persons table, not the Id_P

I expected.

Could you please tell me how to rewrite it to achieve the desired effect?

黄舟
黄舟

人生最曼妙的风景,竟是内心的淡定与从容!

reply all(1)
Ty80

It seems that the db_column parameter cannot specify which field to use as a foreign key (I guess the poster has used sqlalchemy),

Check the django ForeignKey document for this parameter

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.

So just change db_column to to_field

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!