Jér*_*ôme 4 python serialization marshmallow
我想知道如何序列化nest的字典Schema。
天真的,我希望像这样的语法能起作用:
fields.List(Schema)
fields.Dict(Schema)
Run Code Online (Sandbox Code Playgroud)
或许
fields.List(fields.Nested(Schema))
fields.Dict(fields.Nested(Schema))
Run Code Online (Sandbox Code Playgroud)
序列化的列表,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)
Run Code Online (Sandbox Code Playgroud)
我希望我的对象被序列化为
{ 'albums': { 'Hunky Dory': {'year': 1971},
'The Man Who Sold the World': {'year': 1970}},
'name': 'David Bowie'}
Run Code Online (Sandbox Code Playgroud)
目前无法实现,但这是一项功能请求:
并且已经进行了处理:
2017年12月31日:此功能已添加到棉花糖3.0.0b5(https://github.com/marshmallow-code/marshmallow/pull/700)中。
| 归档时间: |
|
| 查看次数: |
3735 次 |
| 最近记录: |