Django 实现外键去除自动添加的后缀‘_id’

作者:MK_chan 时间:2022-11-16 08:06:35 

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/#db-column

来源:https://blog.csdn.net/MK_chan/article/details/88529133

标签:Django,外键,后缀,id
0
投稿

猜你喜欢

  • 纯手工打造CSS像素画

    2009-03-09 12:57:00
  • javascript中正则表达式语法详解

    2024-05-02 16:17:04
  • python实现按键精灵找色点击功能教程,使用pywin32和Pillow库

    2023-11-08 18:30:34
  • Laravel使用PHPQRCODE实现生成带有LOGO的二维码图片功能示例

    2024-05-03 15:28:12
  • go swagger生成接口文档使用教程

    2023-10-20 12:31:35
  • Golang操作Kafka的实现示例

    2024-05-22 10:18:48
  • PHP utf-8编码问题,utf8编码,数据库乱码,页面显示输出乱码

    2024-04-30 09:57:47
  • 网站有效设计的10个原则

    2008-02-11 17:12:00
  • python定时关机小脚本

    2022-09-24 23:38:21
  • Python hashlib加密模块常用方法解析

    2022-03-11 05:20:05
  • windows系统mysql压缩包版本安装过程

    2024-01-14 16:47:38
  • Python实现密钥密码(加解密)实例详解

    2022-09-10 12:03:37
  • CSS实现完美垂直居中

    2007-09-22 09:29:00
  • SQL Server附加数据库报错无法打开物理文件,操作系统错误5的图文解决教程

    2024-01-13 04:20:28
  • TensorFlow使用Graph的基本操作的实现

    2023-04-10 22:22:37
  • Golang中的错误处理深入分析

    2024-02-18 20:59:46
  • SQL SERVER2012中新增函数之字符串函数CONCAT详解

    2024-01-23 18:15:23
  • python使用多线程查询数据库的实现示例

    2024-01-21 18:34:59
  • Jquery.TreeView结合ASP.Net和数据库生成菜单导航条

    2024-01-15 01:23:44
  • PHP htmlspecialchars()函数用法与实例讲解

    2023-06-02 16:48:38
  • asp之家 网络编程 m.aspxhome.com