Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
from copy import deepcopy
from marshmallow import Schema, fields
def PartialSchemaFactory(schema_cls):
schema = schema_cls(partial=True)
for field_name, field in schema.fields.items():
if isinstance(field, fields.Nested):
new_field = deepcopy(field)
new_field.schema.partial = True
schema.fields[field_name] = new_field
return schema
class Address(Schema):
street = fields.Str(required=True)
city = fields.Str(required=True)
state = fields.Str(required=True)
zipcode = fields.Str(required=True)
country = fields.Str(required=True)
class User(Schema):
first_name = fields.Str(required=True)
last_name = fields.Str(required=True)
address = fields.Nested(Address)
payload = {
'first_name': 'John',
'address': {
'zipcode': '90210'
}
}
user_schema = PartialSchemaFactory(User)
data, errors = user_schema.load(payload)
assert errors == {}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.