【发布时间】:2018-11-12 14:41:11
【问题描述】:
使用
- Django:1.11
- Python 3.6
- DRF:3.7
- DREST(又名动态休息):1.8
我有一个这样写的序列化器:
class SubProjectAsFKWithAttachedFieldsSerializer(DynamicModelSerializer):
# attached_fields = AttachedFieldSerializer(embed=True, many=True)
try:
scope_object = UgField.objects.get(dotted_path='global.scope')
scopes = DynamicRelationField(
AttachedFieldWithDirectValuesSerializer,
source='attached_fields',
many=True,
embed=True,
read_only=True,
queryset=AttachedField.objects.filter(ug_field=scope_object)
)
except ObjectDoesNotExist:
scopes = DynamicRelationField(AttachedFieldWithDirectValuesSerializer,
source='attached_fields',
many=True,
read_only=True,
embed=True)
目前,在我几乎所有的 tests.py 的 setUp 方法中,我都有
self.global_scope_field = UgFieldFactory(dotted_path='global.scope', name='Scope')
由于某种原因,这一行
scope_object = UgField.objects.get(dotted_path='global.scope')
尽管我已经使用DjangoModelFactory“实例化”了,但仍然失败
我应该怎么做才能确保在我运行测试时该行始终通过?
更新
- 只是指出我实际上有一个 UgField 记录,其中包含字符串
global.scope作为字段dotted_path的值。 - 只有当我运行
python manage.py test时,我才会遇到这个问题。 - 当我正确运行应用程序时,没有问题。
我也试过设置
(self.global_scope_field, created) = UgField.objects.get_or_create(dotted_path='global.scope', name='Scope')
在我的setUp 方法中。
但是我遇到了同样的问题
【问题讨论】:
-
erm 我实际上有一个 UgField 记录,它的字符串
global.scope作为字段dotted_path的值。当我正确运行应用程序时,没有问题。只有在测试期间我才会遇到这个问题 -
也许在测试时记录不存在,但在运行时它已经存在,所以你得到一个不同的序列化器?也许在测试框架的不同点初始化它?在课堂上使用
try只是......粗略,虽然很聪明。我希望它所做的报告在这种情况下是准确的,我没有经验。也许它实际上在 except: 字段中的代码上抛出了一个异常
标签: django django-rest-framework dynamic-rest