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

相关文章

Python采用Django开发自己的博客系统

Python采用Django开发自己的博客系统

好久之前就想做一下自己的博客系统了,但是在网上查了查好像是需要会一些Node.js的相关知识,而且还要安装辣么多的库什么的,就不想碰了。但是我遇到了Django这么一款神器,没想到我的博...

python输出100以内的质数与合数实例代码

具体代码如下所述: __author__ = 'Yue Qingxuan' # -*- coding: utf-8 -*- #求质数 p=[2] for i in range(2,1...

python文件选择对话框的操作方法

python文件选择对话框的操作方法

对于python的tkinter库来说,如果需要弹出文件选择框,我们需要引入一下tkinter.filedialog包,让用户直观地先择一个或者多个文件或者保存文件等操作。 常见的文件选...

关于python列表增加元素的三种操作方法

 1、insert方法,该方法包含两个参数,第一个参数为插入的位置参数,第二个参数为插入内容 a = [0,0,0] b = [1,2,3] a.insert(0,b) p...

深入浅析python继承问题

有如下的代码: class p1: def __init__(self,a,b): print("init in p1") self.a1=a self.b1=b self.f1()...