棉花糖:嵌套模式的格言

2024-10-01 11:36:15 发布

您现在位置:Python中文网/ 问答频道 /正文

我想知道如何序列化嵌套的Schema的dict。在

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

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

或者也许

^{pr2}$

{cd3>

例如,假设我的对象是这样定义的:

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。)


Tags: the对象namefieldsalbum序列化isschema