棉花糖田依赖

marshmallow field depedency

我有一个非常独特的问题,在互联网上搜索后我找不到我正在寻找的解决方案。我需要在字段之间创建依赖关系。即如果您为 field1 提供一个值,那么您必须为 field2 和 field3 提供值。全有或全无类型的东西。

class MySchema(Schema):
   field1 = field.String(load_from='field1')
   field2 = field.String(load_from='field2')
   field3 = field.String(load_from='field3')
   other_field = field.String(required=True)

你需要schema-level validation.

class MySchema(Schema):
    field1 = field.String()
    field2 = field.String()
    field3 = field.String()
    other_field = field.String(required=True)

    @validates_schema
    def validate_required_fields(self, data):
    if 'field1' in data:
        missing_fields = [f for f in ('field2', 'field3') if f not in data]
        if missing_fields:
            raise ValidationError('Missing fields: {}'.format(missing_fields))

(顺便说一句,如果是字段名称,则无需指定 load_from。)

@Jonathan Rys。这是我最初的解决方案,它不干净但有效,但我推荐@Jerome Code。

 @pre_load(pass_many=True)
    def validate_existing_account_info(self, data, many):
        print(data)

        #raise ValidationError(data)
        if 'field1' not in data and 'field2' not in data and 'field3' not in data:
            pass
        elif 'field1' in data and 'field2' not in data or 'field3' not in data:
            raise ValidationError("Must provide all the required info")
        elif 'field3' in data and 'field1' not in data or 'field2' not in data:
            raise ValidationError("Must provide all the required info")
        elif 'field2' in data and 'field1' not in data or 'field3' not in data:
            raise ValidationError("Must provide all the required info")