Marshmallow: Dict of nested Schema

Jérôme picture Jérôme · Jun 27, 2016 · Viewed 7.6k times · Source

I'm wondering how to serialize a dict of nested Schema.

Naively, I would expect syntaxes like this to work:

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

or maybe

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

Serializing a list of Schema can be achieved through Nested(Schema, many=True), but I don't know about a dict of Schema.

Assume, for example's sake, that my object is defined like this:

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)

I expect my object to be serialized as

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

(Question also discussed on GitHub.)

Answer