我今天遇到了同样的问题,我想出了这个解决方案:
class ValueField(fields.Field):
def _deserialize(self, value, attr, data, **kwargs):
if isinstance(value, str) or isinstance(value, list):
return value
else:
raise ValidationError('Field should be str or list')
class Foo(Schema):
value = ValueField()
other_field = fields.Integer()
您可以创建自定义字段并重载_deserialize
方法,以便验证代码是否isinstance
所需的类型。
我希望它对你有用。
foo.load({'value': 'asdf', 'other_field': 1})
>>> {'other_field': 1, 'value': 'asdf'}
foo.load({'value': ['asdf'], 'other_field': 1})
>>> {'other_field': 1, 'value': ['asdf']}
foo.load({'value': 1, 'other_field': 1})
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "/Users/webinterpret/Envs/gl-gs-onboarding-api/lib/python3.7/site-packages/marshmallow/schema.py", line 723, in load
data, many=many, partial=partial, unknown=unknown, postprocess=True
File "/Users/webinterpret/Envs/gl-gs-onboarding-api/lib/python3.7/site-packages/marshmallow/schema.py", line 904, in _do_load
raise exc
marshmallow.exceptions.ValidationError: {'value': ['Field should be str or list']}