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 urllib 链接中有中文的问题

环境python3,开发平台pycharm,使用urllib时,当url中存在中文时会出现以下错误: UnicodeEncodeError: 'ascii' codec can't...

python实现数独游戏 java简单实现数独游戏

python实现数独游戏 java简单实现数独游戏

 使用python和java实现数独游戏,有比较才有收获哦。 1、Python版 #--coding:utf-8-- import random import itert...

Python SQLite3数据库日期与时间常见函数用法分析

本文实例讲述了Python SQLite3数据库日期与时间常见函数。分享给大家供大家参考,具体如下: import sqlite3 #con = sqlite3.connect('e...

Python实现基本数据结构中栈的操作示例

Python实现基本数据结构中栈的操作示例

本文实例讲述了Python实现基本数据结构中栈的操作。分享给大家供大家参考,具体如下: #! /usr/bin/env python #coding=utf-8 #Python实现基...

解决每次打开pycharm直接进入项目的问题

解决每次打开pycharm直接进入项目的问题

找到对应页面,将Reopen last project on startup前面的勾去掉 以上这篇解决每次打开pycharm直接进入项目的问题就是小编分享给大家的全部内容了,希望能给大...