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

周叙
周叙
发布时间:2026-10-13 | 6人浏览过
原创

本文介绍 Django 中 ForeignKey 默认自动添加 _id 后缀的行为,并通过 db_column 参数自定义数据库列名,解决原生 SQL 或模型映射时的命名冲突问题。

Django 外键默认命名行为

在 Django 框架中,当模型定义使用外键 ForeignKey 时,系统会自动为当前字段名称追加 _id 后缀,生成对应的数据库列名。

使用 db_column 参数自定义列名

通常情况下,这种自动生成的命名方式不会影响正常使用。但在某些特定场景下,例如需要编写原生 SQL 查询,或者将已存在的数据库表直接映射到 Django models 时,这种自动添加的后缀可能会导致列名不匹配。针对这一需求,Django 提供了 db_column 参数来覆盖默认的命名规则。


f = models.ForeignKey(AnotherModel, db_column='f')

通过指定 db_column 参数,可以明确指定数据库中的实际列名,从而避免自动添加 _id 后缀。

Django 官方文档对此参数的解释如下:

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

以上内容介绍了 Django 中如何去除外键自动添加的 _id 后缀。希望这些信息能为您提供参考,并支持本站分享的技术内容。

相关标签:

本站声明

本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。

Python 相关产品和应用

全部下载

专题列表