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中字典(dict)和列表(list)的排序方法实例

一、对列表(list)进行排序 推荐的排序方式是使用内建的sort()方法,速度最快而且属于稳定排序复制代码 代码如下:>>> a = [1,9,3,7,2,0,5]&...

使用Python3 编写简单信用卡管理程序

1、程序执行代码: #Author by Andy #_*_ coding:utf-8 _*_ import os,sys,time Base_dir=os.path.dirname...

python测试驱动开发实例

本文实例讲述了python测试驱动开发的方法,分享给大家供大家参考。具体方法如下: import unittest from main import Sample class S...

详解基于python-django框架的支付宝支付案例

详解基于python-django框架的支付宝支付案例

一. 开发前的准备 1. 必须了解的知识 SDK:软件开发工具包,可以为开发者提供快速开发的工具 沙箱环境:也就是测试环境 支付宝支付金额的精度:小数点后两位(面试)...

python实现视频读取和转化图片

1)视频读取 import cv2 cap = cv2.VideoCapture('E:\\Video\\20000105_224116.dav') #地址 while(True...