Django:运行测试时迁移期间的ContentTypes

时间:2016-10-31 15:09:32

标签: python django postgresql

我使用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行?

1 个答案:

答案 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()个对象并迭代。