You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Django自动生成过长索引名引发MongoDB OperationFailure问题求助

解决Django自动生成过长索引名导致MongoDB报错的问题

针对django_content_type_app_label_model_76bd3d3b_uniq这类自动生成的过长约束名触发MongoDB命名空间长度限制的问题,可通过以下两种方式解决:

方法一:通过自定义迁移修改约束名

  1. 生成空迁移文件:
    python manage.py makemigrations --empty contenttypes
    
  2. 打开生成的迁移文件,替换原有内容为以下代码(注意修改dependencies中的迁移版本为你当前contenttypes应用的最新迁移):
    from django.db import migrations, models
    
    class Migration(migrations.Migration):
        dependencies = [
            ('contenttypes', '0002_remove_content_type_name'),
        ]
    
        operations = [
            migrations.RemoveConstraint(
                model_name='contenttype',
                name='django_content_type_app_label_model_76bd3d3b_uniq',
            ),
            migrations.AddConstraint(
                model_name='contenttype',
                constraint=models.UniqueConstraint(
                    fields=('app_label', 'model'),
                    name='ct_app_model_uniq',  # 自定义短约束名
                ),
            ),
        ]
    
  3. 执行迁移:
    python manage.py migrate
    

方法二:自定义ContentType模型(适合新项目)

  1. 在你的应用中创建自定义ContentType模型:
    from django.contrib.contenttypes.models import ContentTypeManager, AbstractContentType
    
    class MyContentType(AbstractContentType):
        objects = ContentTypeManager()
    
        class Meta:
            db_table = 'django_content_type'
            constraints = [
                models.UniqueConstraint(
                    fields=['app_label', 'model'],
                    name='ct_app_model_uniq'
                )
            ]
    
  2. 在settings.py中配置替换内置模型:
    CONTENT_TYPES_MODEL = 'your_app_name.MyContentType'
    
  3. 执行初始化迁移:
    python manage.py makemigrations
    python manage.py migrate
    

注意事项

  • 执行迁移前建议备份数据库,避免数据风险。
  • 自定义约束名需保证唯一性,且长度符合MongoDB要求(命名空间总长度不超过128字符)。

内容的提问来源于stack exchange,提问作者叶同学

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.29 16:17:29