我试图通过仅从嵌套项中获取一个字段来将嵌套对象列表序列化为标量值。而不是[{key: value}, ...]
我想收到[value1, value2, ...]
.
代码:
from marshmallow import *
class MySchema(Schema):
key = fields.String(required=True)
class ParentSchema(Schema):
items = fields.Nested(MySchema, only='key', many=True)
鉴于上述模式,我想序列化一些数据:
>>> data = {'items': [{'key': 1}, {'key': 2}, {'key': 3}]}
>>> result, errors = ParentSchema().dump(data)
>>> result
{'items': ['1', '2', '3']}
这按预期工作,给了我标量值列表。但是,当尝试使用上述模型反序列化数据时,数据突然无效:
>>> data, errors = ParentSchema().load(result)
>>> data
{'items': [{}, {}, {}]}
>>> errors
{'items': {0: {}, '_schema': ['Invalid input type.', 'Invalid input type.', 'Invalid input type.'], 1: {}, 2: {}}}
我是否缺少任何配置选项,或者这根本不可能?