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?
PHP中文网2017-05-18 10:48:04
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