gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 17:49:41 35 4
gpt4 key购买 nike

我使用 contrib.contenttypes 框架将 ForeignKey 迁移到 GenericForeignKey。要访问我需要迁移数据的 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 行在测试数据库迁移中存在?

最佳答案

这就是最终对我有用的东西。首先,导入 update_contenttypes:

from django.contrib.contenttypes.management import update_contenttypes

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

dependencies = [
('contenttypes', '0001_initial'),
...
]

最后,在forward迁移函数中(在迁移operations中通过RunPython调用):

# 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 运行上述代码。您可以使用 apps.get_app_configs() 获取所有 app_config 对象并迭代。

关于python - Django:运行测试时迁移期间的 ContentTypes,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40344994/

35 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com