gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 22:30:22 24 4
gpt4 key购买 nike

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

最佳答案

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

关于python - 如何将上下文传递给 Marshmallow 中的嵌套序列化程序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25163883/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com