gpt4 book ai didi

python - Marshmallow:嵌套模式字典

转载 作者:行者123 更新时间:2023-12-02 06:08:44 28 4
gpt4 key购买 nike

我想知道如何序列化嵌套Schema的字典。

天真地,我希望这样的语法能够工作:

fields.List(Schema)
fields.Dict(Schema)

或者也许

fields.List(fields.Nested(Schema))
fields.Dict(fields.Nested(Schema))

序列化Schema列表可以通过Nested(Schema, Many=True)来实现,但我不知道dict > 架构

假设,例如,我的对象定义如下:

from marshmallow import Schema, fields, pprint

class AlbumSchema(Schema):
year = fields.Int()

class ArtistSchema(Schema):
name = fields.Str()

# What should I write, here?

# This won't work
albums = fields.Nested(AlbumSchema(), many=True)

# If I write this, AlbumSchema is ignored, so this is equivalent to
albums = fields.Dict(AlbumSchema(), many=True)
# this, which is not satisfying (AlbumSchema unused)
albums = fields.Dict()
# This is not the way either
albums = fields.Dict(fields.Nested(AlbumSchema))


album_1 = dict(year=1971)
album_2 = dict(year=1970)
bowie = dict(name='David Bowie',
albums={
'Hunky Dory': album_1,
'The Man Who Sold the World': album_2
}
)

schema = ArtistSchema()
result = schema.dump(bowie)
pprint(result.data, indent=2)

我希望我的对象被序列化为

{ 'albums': { 'Hunky Dory': {'year': 1971},
'The Man Who Sold the World': {'year': 1970}},
'name': 'David Bowie'}

(问题还讨论了 on GitHub 。)

最佳答案

关于python - Marshmallow:嵌套模式字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38048775/

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