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

yipeiwu_com6年前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/

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

相关文章

opencv python 图像去噪的实现方法

opencv python 图像去噪的实现方法

在早先的章节里,我们看到很多图像平滑技术如高斯模糊,Median模糊等,它们在移除数量小的噪音时在某种程度上比较好用。在这些技术里,我们取像素周围的一小部分邻居,做一些类似于高斯平均权重...

Python 从相对路径下import的方法

例如我们有如下结构的文件: pkg/ __init__.py libs/ some_lib.py __init__.py components/ code.py __i...

详解python播放音频的三种方法

第一种 使用pygame模块 pygame.mixer.init() pygame.mixer.music.load(self.wav_file) pygame.mix...

Python 自动化表单提交实例代码

Python 自动化表单提交实例代码

今天以一个表单的自动提交,来进一步学习selenium的用法 练习目标   0)运用selenium启动firefox并载入指定页面(这部分可查看本人文章 http://www.cnbl...

Python 实现引用其他.py文件中的类和类的方法

#HelloWorld是文件名称,Hello是类 from HelloWorld import Hello 调用,Hello类的方法: >>> h = Hel...