7

从他们的嵌套示例中:

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博客时似乎没有获得上下文。如何将上下文传递给嵌套的序列化程序?

4

1 回答 1

10

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}}
于 2014-10-20T03:22:10.097 回答