I struggle to understand how to handle unknown fields when the Schema
is passed a list of objects for validation. I got so far :
class MySchema(Schema):
# fields ...
@marshmallow_decorators.validates_schema(pass_original=True)
def check_unknown_fields(self, data, original_data):
if isinstance(original_data, list):
for dct in original_data:
self._assert_no_unknown_field(dct)
else:
self._assert_no_unknown_field(original_data)
def _assert_no_unknown_field(self, dct):
unknown = set(dct.keys()) - set(self.fields)
if unknown:
raise MarshmallowValidationError('Unknown field', unknown)
But that obviously doesn't work, as the validator is ran for all items in the list every time. Therefore the first error will be caught, and returned on all items :
items = [
{'a': 1, 'b': 2, 'unknown1': 3},
{'a': 4, 'b': 5, 'unknown2': 6},
]
errors = MySchema(many=True).validate(items)
# {0: {'unknown1': ['Unknown field']}, 1: {'unknown1': ['Unknown field']}}
I was trying to think of a way to get only the single item from original_data
corresponding to the data
argument and validate only that one, but I can't really do that, as items have no id, or field that would make them searchable ...
Am I missing something? Is there a solution to this?