如何将上下文传递给Marshmallow中的嵌套序列化器?

时间:2014-08-06 15:07:12

标签: python marshalling marshmallow

来自他们的嵌套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似乎没有得到上下文。 如何将上下文传递给嵌套的序列化程序?

1 个答案:

答案 0 :(得分:6)

marshmallow 1.0.0-a起,嵌套字段的FunctionMethod字段会从其父级继承上下文。

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