6

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

天真地,我希望这样的语法可以工作:

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

或者可能

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

序列化一个列表Schema可以通过 实现,Nested(Schema, many=True)但我不知道一个dictSchema

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

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'}

(问题也在GitHub 上讨论过。)

4

1 回答 1

8

目前这是不可能的,但这是一个功能请求:

它已经在工作了:

2017-12-31:此功能已添加到 Marshmallow 3.0.0b5 ( https://github.com/marshmallow-code/marshmallow/pull/700 )。

于 2016-08-28T16:34:29.973 回答