pythonmarshmallow

marshmallow field dependency


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)

Solution

  • 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.)