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

相关文章

python3实现磁盘空间监控

本文实例为大家分享了python3磁盘空间监控的具体代码,供大家参考,具体内容如下 软硬件环境 python3 apscheduler 前言 在做频繁操作磁盘的python项目时,经...

Python语法分析之字符串格式化

前序 There should be one - and preferably only one - obvious way to do it. ———— the Zen of Pyt...

Python之读取TXT文件的方法小结

方法一: <span style="font-size:14px;">#read txt method one f = open("./image/abc.txt")...

python 对象和json互相转换方法

一、python对json的支持 从python2.6开始,python标准库中添加了对json的支持,操作json时,只需要import json即可。 二、python对象转换成js...

学习python处理python编码问题

概括、从python1.6开始就可以处理unicode字符了。 一、几种常见的编码格式。 1.1、ascii,用1个字节表示。 1.2、UTF-8,用1个至三个字节表示,表示ascii码...