棉花糖:嵌套Schema的词典

时间:2016-06-27 08:06:30

标签: python serialization marshmallow

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

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

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

或者

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

可以通过Schema序列化Nested(Schema, many=True)列表,但我不了解dict Schema

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

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

1 个答案:

答案 0 :(得分:3)