Python棉花糖验证在项目索引上展开

时间:2017-03-01 13:10:31

标签: python serialization marshmallow

我有类似下面的架构:

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_loadvalidates_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'
            )

0 个答案:

没有答案