7

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?

3
  • At the moment I have to serialise the nested attribute in a method. Is this a good solution?
    – DiogoNeves
    Aug 6, 2014 at 15:09
  • 1
    This is how I would handle it.
    – justanr
    Sep 28, 2014 at 18:55
  • stackoverflow.com/a/59027452/5698202 is the way to go in case you can't pass context to the OuterSchema and/or need to set when control is within the OuterSchema. Jul 23, 2021 at 10:32

1 Answer 1

10

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}}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.