我有类似下面的架构:
class MySchema(Schema):
nested = fields.Nested(
NestedSchema, required=True, many=True, validate=[validate.Length(min=1)]
)
class NestedSchema(Schema):
somefield = fields.Field()
somefield2 = fields.Field()
我希望我的somefield
字段是必需的,但仅适用于列表中的第一项。有谁知道如何实现这一目标?
如果可能,我还想将我的错误消息保留在正确的元素中,我返回错误dict:
{
'nested': {
0: {
'somefield': ['This field is required']
}
}
}
我已尝试使用pre_load
和validates_schema
进行此操作,但我无法在错误字典中将消息放在适当的位置。问题是somefield
中出现_schema
错误或类似错误:
{
'nested': {
'somefield': ['This field is required']
}
}
示例预加载:
@pre_load(pass_many=True)
def validate_somefield(self, data, many):
try:
address = data[0]
except IndexError:
pass
else:
if address.get('somefield') is None:
raise ValidationError(
'somefield is required for first element'
)