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

删除Django模型后,如何移除关联MyEnum枚举类且避免迁移报错?

问题:移除Django模型依赖的枚举类后,如何避免从头执行迁移时报错?

我之前创建了带选项的模型:

class MyEnum(StrEnum):
    CREATE = "create"
    DELETE = "delete"

class ShareHistory(models.Model):
    action = models.TextField(choices=MyEnum.get_choices())
    created_at = models.DateTimeField(auto_now_add=True, auto_created=True)

后来发现不再需要这个模型,删除模型类后执行makemigrations和migrate就能删掉对应数据表。但我想同时移除MyEnum枚举类,直接删除的话,其他人从头执行迁移会报错——因为初始迁移文件里直接依赖了MyEnum。迁移文件片段如下:

class Migration(migrations.Migration):
    initial = True

    dependencies = [
        ('contenttypes', '0002_remove_content_type_name'),
    ]

    operations = [
        migrations.CreateModel(
            name='ShareHistory',
            fields=[
                ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('created_at', models.DateTimeField(auto_created=True, auto_now_add=True)),
                ('action', models.TextField(choices=[
                    (MyEnum['CREATE'],
                     MyEnum['CREATE']),
                    (MyEnum['DELETE'],
                     MyEnum['DELETE']),
                ])),
            ],
        ),
    ]

解决方案

1. 固化迁移文件中的枚举引用

直接修改初始迁移文件,把所有MyEnum的引用替换成对应的字符串值,让choices变成硬编码的元组列表。修改后的迁移片段如下:

class Migration(migrations.Migration):
    initial = True

    dependencies = [
        ('contenttypes', '0002_remove_content_type_name'),
    ]

    operations = [
        migrations.CreateModel(
            name='ShareHistory',
            fields=[
                ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('created_at', models.DateTimeField(auto_created=True, auto_now_add=True)),
                ('action', models.TextField(choices=[
                    ("create", "create"),
                    ("delete", "delete"),
                ])),
            ],
        ),
    ]

这样迁移文件就完全脱离了对MyEnum的依赖。

2. 删除模型和枚举类

现在可以放心删除ShareHistory模型类和MyEnum枚举类,然后在终端执行:

python manage.py makemigrations
python manage.py migrate

这会生成删除数据表的迁移文件,并执行迁移完成清理。

3. 同步团队迁移文件

把修改后的初始迁移文件和新生成的删除迁移文件提交到版本控制工具,团队其他成员拉取代码后,执行migrate就能正常完成迁移流程,不会因为缺少MyEnum报错。

内容的提问来源于stack exchange,提问作者pepe_botika69

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 22:50:03