我使用ForeignKey
框架将GenericForeignKey
迁移到contrib.contenttypes
。要访问我需要迁移数据的ContentType
对象,我使用了以下代码:
ContentType = apps.get_model('contenttypes', 'ContentType')
my_model_content_type = ContentType.objects.get(
app_label='my_app',
model='my_model'
)
当我运行manage.py migrate
时迁移工作正常,然后我可以在shell中使用更新的模型而不会出现问题。
但是,当我尝试运行manage.py test
时,我在ContentTypes.object.get()
行中收到以下错误:
__fake__.DoesNotExist: ContentType matching query does not exist.
当时查询ContentType.objects.all()
会返回一个空的查询集。
我已经尝试过(在SO中另一个回答的指示)在我的查询之前运行它,但无济于事:
update_contenttypes(apps.app_configs['contenttypes'])
update_contenttypes(apps.app_configs['my_app'])
如何确保测试数据库迁移中此时存在ContentType
行?
答案 0 :(得分:5)
这最终为我工作。首先,导入update_contenttypes
:
from django.contrib.contenttypes.management import update_contenttypes
其次,将初始ContentType
迁移列为依赖项:
dependencies = [
('contenttypes', '0001_initial'),
...
]
最后,在forward
迁移功能中(在迁移RunPython
中通过operations
调用):
# Ensure ContentType objects exist at this point:
app_config = apps.get_app_config('my_app')
app_config.models_module = app_config.models_module or True
update_contenttypes(app_config)
您可能需要为多个app_config
运行上述代码。您可以使用app_config
获取所有apps.get_app_configs()
个对象并迭代。