当前位置:首页 » python教程 » 正文

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

看: 753次  时间:2021-02-22  分类 : python教程

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'就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持python博客。

标签:django  

<< 上一篇 下一篇 >>

搜索

推荐资源

  Powered By python教程网   鲁ICP备18013710号
python博客 - 小白学python最友好的网站!