Last active
October 5, 2015 18:35
-
-
Save ramnes/89245fbd9f2dfff52a78 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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