marshmallow field depedency

Question:

I have a very unique problem and after searching the internet I can’t find the solution I am looking for. I need to create a dependency between the fields. i.e If you provide a value for field1 then you MUST provide values for field2 and field3. all or nothing type of thing.

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)
Asked By: devopsdream

||

Answers:

You need 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))

(BTW, no need to specify load_from if it’s the field name.)

Answered By: Jérôme

@Jonathan Rys. This is the solution I originally had it’s not clean but it works but I recommend @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")
Answered By: devopsdream
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.