来自他们的嵌套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})
序列化博客时,UserSerializer
似乎没有得到上下文。
如何将上下文传递给嵌套的序列化程序?
答案 0 :(得分:6)
自marshmallow 1.0.0-a起,嵌套字段的Function
和Method
字段会从其父级继承上下文。
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}}