From their nested example:
class BlogSerializer(Serializer):
title = fields.String()
author = fields.Nested(UserSerializer)
# This is different! I'm passing in a context
serialized = BlogSerializer(blog, context={'test': 1})
The UserSerializer
doesn't seem to get the context when serializing the blog.
How do I pass the context down to the nested serializers?
As of marshmallow 1.0.0-a, nested field's Function
and Method
fields inherit context from their parent.
from marshmallow import Schema, fields, pprint
class InnerSchema(Schema):
value = fields.Function(lambda val, ctx: 'foo' in ctx['from_outer'])
class OuterSchema(Schema):
inner = fields.Nested(InnerSchema)
schema = OuterSchema(context={'from_outer': 'foo'})
obj = {'inner': {}}
result = schema.dump(obj)
pprint(result.data) # {"inner": {"value": true}}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With