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解析xml文件实例分享

python解析xml文件实例分享

复制代码 代码如下:def get_area_list(self):        """获取地域省份和城市名称字典...

python自制包并用pip免提交到pypi仅安装到本机【推荐】

不得不说python的自制包的相关工具真是多且混乱,什么setuptools,什么distutils,什么wheel,什么egg!!怎么有这么多啊?? 而且我的需求且且是创建一个自制包管...

Python实现正则表达式匹配任意的邮箱方法

Python实现正则表达式匹配任意的邮箱方法

首先来个简单的例子,利用Python实现匹配163邮箱的代码: #-*- coding:utf-8 -*- __author__ = '杨鑫' import re text = in...

python之django母板页面的使用

其实就是利用{% block xxx %}   {% endblock %}的方式定义一个块,相当于占位。存放在某个html中,比如base.html 然后在需要实现...

python获取点击的坐标画图形的方法

获取输入的五个点画五边形 def pentagonUpdate(): p = {} win = GraphWin("Click", 800, 300)#后面两个值为窗体的长和...