Skip to content

Instantly share code, notes, and snippets.

@ramnes
Last active October 5, 2015 18:35
Show Gist options
  • Save ramnes/89245fbd9f2dfff52a78 to your computer and use it in GitHub Desktop.
Save ramnes/89245fbd9f2dfff52a78 to your computer and use it in GitHub Desktop.
from marshmallow.fields import Nested as BaseNested
class Nested(BaseNested):
"""An overloaded Nested field that can handle more than a single schema.
By giving it a list of schemas, it will iterate through them to find one
that matches with the input data. It raises an error if the data doesn't
correspond to any schema.
"""
def _deserialize(self, value, attr, data):
try:
return super(Nested, self)._deserialize(value, attr, data)
except ValueError:
if isinstance(self.nested, list):
for schema in self.nested:
if isinstance(schema, type):
schema = schema()
data, errors = schema.load(value)
if not errors:
return data
self.fail("validator_failed")
raise
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment