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

yipeiwu_com5年前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设计】。

相关文章

Python json 错误xx is not JSON serializable解决办法

Python json 错误xx is not JSON serializable解决办法 在使用json的时候经常会遇到xxx  is not JSON serializab...

关于python3中setup.py小概念解析

关于 python setup.py bdist python setup.py sdist 两者的区别 sdist 指的是source dist 即源码发布,带s...

python 字典套字典或列表的示例

文件f1 A 1 a A 1 b A...

Pycharm无法使用已经安装Selenium的解决方法

Pycharm无法使用已经安装Selenium的解决方法

电脑C盘安装python27的时候也安装了selenium,但是最近刚刚使用工具Pycharm,新建工程后,然后建立.py文件后,使用语句:from selenium.webdriver...

Python3.6正式版新特性预览

按照Python官网上的计划,Python3.6正式版期望在2016-12-16号发布,也就是这周五。从去年的5月份开始,Python3.6版本就已经动手开发了,期间也断断续续的发布了4...