Django测试夹具和内容类型 [英] Django test fixtures and content types
问题描述
我在我的模型中使用django的 ContentType 外键,
,我正在灯具中使用它进行单元测试。
I'm using django's ContentType foreign key in my model, and I'm using it in the fixtures for unit tests.
因此,我必须在我的装置中硬编码 content_type_id ,但是django有时会将其初始化为不同的值,因此我的测试失败。
Therefore, I have to hard-code content_type_id in my fixture, but django sometimes initializes it to a different value and thus my tests fail.
有没有办法安全地预测模型的 content_type_id 或任何其他正确的方式来处理这种情况?
So is there a way to safely predict the content_type_id of the model or any other proper way to handle such situations?
推荐答案
使用自然键: https: //docs.djangoproject.com/en/dev/topics/serialization/#natural-keys
大多数文档是指如何添加功能对于您自己的模型,但 ContentType
已经支持他们,所以只需添加 dumpdata 管理命令:
Most of the documentation refers to how to add the capability to your own models, but ContentType
already supports them so just add --natural-foreign
to your dumpdata
management command:
$ python manage.py dumpdata myapp --indent=4 --natural-foreign
这篇关于Django测试夹具和内容类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!