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

sle*_*ica 12 python django postgresql

我使用框架ForeignKey将a 迁移到a .要访问我需要迁移数据的对象,我使用了以下代码:GenericForeignKeycontrib.contenttypesContentType

ContentType = apps.get_model('contenttypes', 'ContentType')

my_model_content_type = ContentType.objects.get(
    app_label='my_app',
    model='my_model'
)
Run Code Online (Sandbox Code Playgroud)

我运行时迁移工作manage.py migrate,然后我可以在shell中使用更新的模型而不会出现问题.

但是,当我尝试运行时manage.py test,我ContentTypes.object.get()在行中收到以下错误:

__fake__.DoesNotExist: ContentType matching query does not exist.
Run Code Online (Sandbox Code Playgroud)

ContentType.objects.all()那时查询返回一个空的查询集.

我已经尝试过(在SO中另一个回答的指示)在我的查询之前运行它,但无济于事:

update_contenttypes(apps.app_configs['contenttypes'])
update_contenttypes(apps.app_configs['my_app'])
Run Code Online (Sandbox Code Playgroud)

如何确保ContentType测试数据库迁移中的那些行存在?

sle*_*ica 6

这就是最终为我工作的东西.一,进口update_contenttypes:

from django.contrib.contenttypes.management import update_contenttypes
Run Code Online (Sandbox Code Playgroud)

其次,将初始ContentType迁移列为依赖项:

dependencies = [
    ('contenttypes', '0001_initial'),
    ...
]
Run Code Online (Sandbox Code Playgroud)

最后,在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)
Run Code Online (Sandbox Code Playgroud)

您可能需要为多个代码运行上述代码app_config.您可以app_config使用apps.get_app_configs()和迭代获取所有对象.

  • https://code.djangoproject.com/ticket/28092 重命名为 create_contenttypes (2认同)