Django 迁移:在引用已删除的模型字段的数据迁移中崩溃
Django migrations: crashing in a data migration refering to an already removed model field
正在创建测试数据库,Django 引发此异常
django.core.exceptions.FieldError: Cannot resolve keyword 'xxx' into field. Choices are: ...
失败的迁移是自定义迁移,将数据从(比方说)ModelA
移动到 ModelB
:
def forwards(apps, schema_editor):
...
prev_list = ModelA.objects.all().values_list('xxx').distinct()
for item in prev_list:
ModelB(xxx=item).save()
我的下一个动作已经过检查 ModelA
没问题,没有名为 XXX
的字段
class ModelA(Model):
# no field named xxx
挖掘一下这里发生的事情:
ModelA
曾经有一个名为 xxx
的字段
- 有一个迁移试图创建
ModelB
行读取 ModelA.xxx
ModelA
没有这样的字段,因为稍后的迁移会删除该字段,所以我没有在我的模型中声明该字段。
为什么创建测试数据库失败(来自 python manage.py test
)?
我怎样才能解决这个问题?
你不应该直接导入ModelA
,而是像下面这样导入历史版本(参见编写迁移的文档here)。
ModelA = apps.get_model('myapp', 'ModelA')
根据 docs,如果你 运行 遇到这个问题,你可以编辑一个旧的迁移:
...historical model problems may not be immediately obvious. If you run into this kind of failure, it’s OK to edit the migration to use the historical models rather than direct imports and commit those changes.
正在创建测试数据库,Django 引发此异常
django.core.exceptions.FieldError: Cannot resolve keyword 'xxx' into field. Choices are: ...
失败的迁移是自定义迁移,将数据从(比方说)ModelA
移动到 ModelB
:
def forwards(apps, schema_editor):
...
prev_list = ModelA.objects.all().values_list('xxx').distinct()
for item in prev_list:
ModelB(xxx=item).save()
我的下一个动作已经过检查 ModelA
没问题,没有名为 XXX
的字段
class ModelA(Model):
# no field named xxx
挖掘一下这里发生的事情:
ModelA
曾经有一个名为xxx
的字段
- 有一个迁移试图创建
ModelB
行读取ModelA.xxx
ModelA
没有这样的字段,因为稍后的迁移会删除该字段,所以我没有在我的模型中声明该字段。
为什么创建测试数据库失败(来自 python manage.py test
)?
我怎样才能解决这个问题?
你不应该直接导入ModelA
,而是像下面这样导入历史版本(参见编写迁移的文档here)。
ModelA = apps.get_model('myapp', 'ModelA')
根据 docs,如果你 运行 遇到这个问题,你可以编辑一个旧的迁移:
...historical model problems may not be immediately obvious. If you run into this kind of failure, it’s OK to edit the migration to use the historical models rather than direct imports and commit those changes.