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. 急急国王什么梗 我是急急急急急急国王梗内涵出处介绍2. 微博2输入框一些问题3. 登录mysql-front出现以下错误4. python 中文乱码问题5. php - mysql中,作为主键的字段,用int类型,是不是比用char类型的效率更高?6. mysql - 博客文章标签表结构设计问题7. linux - 阿里云服务器上的mysql服务在客户端只能通过ssh证书连接后才能使用8. python - 图片爬虫时候遇到问题 urllib.request.urlretrieve 下载到指定文件夹不成功?9. python - 请问matplotlib.pyplot.save的路径如何更改10. 创建mysqli对象与数据库连接 - 出错

网公网安备