从他们的嵌套示例:
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.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}}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句