Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass context to nested serializers in Marshmallow?

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?

like image 924
DiogoNeves Avatar asked Aug 06 '14 15:08

DiogoNeves


1 Answers

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}}
like image 111
Steve L Avatar answered Oct 13 '22 18:10

Steve L