重命名应用程序后进行迁移时出现 Django 错误

Rup*_*ert 0 python django

我正在处理一个 Django 项目,但在架构中遇到错误。

我正在尝试在自己的包中设置模型。但是,我的应用程序不断给我错误。

一切正常,直到我将模型移动到它们自己的包中并为每个类创建一个文件。

现在,每当我尝试运行时makemigrations,都会收到此错误:

 ValueError: Unhandled pending operations for models:
  model.state (referred to by fields: testadmin.Member.state, testadmin.Organization.state)
Run Code Online (Sandbox Code Playgroud)

我将模型应用程序添加到迁移命令中,它有点工作 - python ./manage.py makemigrations models。但是,现在我遇到了这个新错误。由于某种原因,迁移无法识别State模型。

SystemCheckError: System check identified some issues: ERRORS:
models.Member.state: (fields.E300) Field defines a relation with model 'State', which is either not installed, or is abstract.
models.Organization.state: (fields.E300) Field defines a relation with model 'State', which is either not installed, or is abstract
Run Code Online (Sandbox Code Playgroud)

And*_*ini 5

您已重命名您的应用程序,但未重命名您的表。

Django 将模型的表名构造为<app-name>_<model-name>. 通过更改应用程序的名称,您已更改表名称。Django 现在正在寻找不存在的表。它还抱怨迁移,因为应用的迁移记录在数据库中,并且它们包含对应用程序名称的引用。

您应该手动创建迁移来处理这些更改:

  1. 表的重命名。你可以用AlterModelTable它。

    class Migration(migrations.Migration):
        # ...
        operations = [
            AlterModelTable('<old-app-name>_modelname', '<new-app-name>_modelname'),
            # ...
        ]
    
    Run Code Online (Sandbox Code Playgroud)
  2. 重命名迁移。您必须为此使用该MigrationRecorder.Migration模型。

    def rename_migrations_forwards(apps, schema_editor):
        MigrationRecorder.Migration.objects.filter(app='<old-app-name>').update(app='<new-app-name>')
    
    def rename_migrations_reverse(apps, schema_editor):
        MigrationRecorder.Migration.objects.filter(app='<new-app-name>').update(app='<old-app-name>')
    
    class Migration(migrations.Migration):
        # ...
        operations = [
            # ...
            migrations.RunPython(
                rename_migrations_forwards,
                rename_migrations_reverse,
            ),
        ]
    
    Run Code Online (Sandbox Code Playgroud)

如果您db_table在模型元中覆盖,则可以跳过表的重命名。但是,您不能跳过迁移的重命名。