迁移回滚期间无法从其他应用程序导入 Django 模型

Unable to import Django model from the other app during migration roll-back

我正在为 new_app 创建数据迁移,可以将其回滚。

# This is `new_app` migration
class Migration(migrations.Migration):

    dependencies = [
    ]

    operations = [
        migrations.RunPython(import_data, reverse_code=delete_data)
    ]

此迁移将一些数据添加到其他应用中定义的模型:my_other_app。要导入我想更新或删除记录的模型,我使用 apps.get_model() 方法。

# This is `new_app` migration
def import_data(apps, schema_editor):   
    model = apps.get_model('my_other_app', 'MyModel')

当我应用迁移时,它就像魅力一样。但是当我 运行 尝试使用 :~> manage.py migrate new_app zero 回滚迁移时,我得到异常:LookupError: No installed app with label 'my_other_app'. 回滚代码中的模型导入:

# This is `new_app` migration
def delete_data(apps, schema_editor):
    schema_model = apps.get_model('my_other_app', 'MyModel')

导入模型的代码是一样的,为什么迁移回滚时不起作用?现在我在回滚期间有一个直接模型 import 的解决方法。不知道以后会不会带来麻烦

确保 dependencies 包含来自您引用的其他应用的最新迁移。例如:

dependencies = [
    'my_other_app.0001_initial',
]

此外,请确保 'my_other_app' 在您的 INSTALLED_APPS 设置中。