神剑山庄资源网 Design By www.hcban.com

django在使用外键ForeignKey的时候,会自动给当前字段后面添加一个后缀_id。

正常来说这样并不会影响使用。除非你要写原生sql,还有就是这个表是已经存在的,你只是把数据库中的表映射回models。实际上django提供了这样的一个关键字db_colnum来解决这个问题,你只需要:

f = models.ForeignKey(AnotherModel, db_column='f')

这样就不会自动添加_id这个后缀了。

文档中是这么解释的:

The name of the database column to use for this field. If this isn't given, Django will use the field's name.
If your database column name is an SQL reserved word, or contains characters that aren't allowed in Python variable names – notably, the hyphen – that's OK. Django quotes column and table names behind the scenes.

https://docs.djangoproject.com/en/dev/ref/models/fields/#db-column

以上这篇Django 实现外键去除自动添加的后缀‘_id'就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。

标签:
Django,外键,后缀,_id

神剑山庄资源网 Design By www.hcban.com
神剑山庄资源网 免责声明:本站文章均来自网站采集或用户投稿,网站不提供任何软件下载或自行开发的软件! 如有用户或公司发现本站内容信息存在侵权行为,请邮件告知! 858582#qq.com
神剑山庄资源网 Design By www.hcban.com

评论“Django 实现外键去除自动添加的后缀‘_id’”

暂无Django 实现外键去除自动添加的后缀‘_id’的评论...