gpt4 book ai didi

Django 测试和 ContentType 通用关系装置

转载 作者:行者123 更新时间:2023-12-04 21:16:24 24 4
gpt4 key购买 nike

如何在 Django 单元测试中使用 GenericRelations?

我在互联网上阅读并尝试了无数建议,但无济于事。

这个很有前途Problems with contenttypes when loading a fixture in Django

但是“重置”命令在 Django 1.6 中不再存在

我的项目对 ContentType 使用 GenericForeign 键,对 auth.Users 使用外键。我仅使用 --natural 选项为我的应用程序转储了数据,但这导致了测试数据库中不存在用户的问题。现在我删除了 --natural 选项,而是转储了所有 3 个应用程序 myApp、auth、contenttypes 的数据。当我运行测试时,我得到“无法加载 contenttypes.ContentType(pk=50):列 app_label,模型不是唯一的”。我认为这是由于导入模型时动态创建的内容类型。

使用的命令:

python manage.py dumpdata auth myApp contenttypes --natural --indent=4 > auhtmtmnatural.json

接下来我抛弃了 myApp,auth 离开了 contenttypes。我认为由于 ContentTypes app db 是动态创建的并且我的装置具有自然键,所以这应该可以工作。它没有。

现在我得到:
DeserializationError: Problem installing fixture 'auhtmtmnatural.json': ContentType matching query does not exist.

我如何让带有contetypes的fixutres工作?在测试中使用设置和创建对象更好吗?

最佳答案

使用 content_type: [<app_label>, <model>],而不是 content_type: <hard-coded pk of model>

关于Django 测试和 ContentType 通用关系装置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22563034/

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