Skip to main content
 首页 » 编程设计

python之Django 南 : How can I access models in sub-packages in migrations

2025年05月04日23qq78292959

由于我们的应用程序有很多模型,我们将它们放在模型包的子包中,即 Cheddar 模型不会在 models.Cheddar 中,而是在 models.cheese.Cheddar 中。

我似乎无法在 South 数据迁移中访问这些模型,即使我根据 this answer 创建了一个 models/__init__.py包含行 from cheese import *。

在我的数据迁移文件中,行 for cheddar in orm.Cheddar.objects.all(): 仍然导致以下错误:

AttributeError: The model 'Cheddar' from the app 'core' is not available in this migration. (Did you use orm.ModelName, not orm['app.ModelName']?) 

尝试使用 orm['core.models.cheese.Cheddar'] 会导致此错误:

KeyError: "The model 'cheddar' from the app 'core' is not available in this migration." 

有谁知道如何解决这个问题?

请您参考如下方法:

事实证明,问题在于 Cheddar 模型未在 DataMigration 实例的 models 属性中列出:

class Migration(DataMigration): 
    # ... 
 
    models = { 
        # ... 
    } 

一旦我在其中添加了正确的模型定义(对我来说这是在之前的迁移中),数据迁移就成功了。