【发布时间】:2017-10-26 08:38:13
【问题描述】:
我试图通过仅从嵌套项中获取一个字段来将嵌套对象列表序列化为标量值。而不是[{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: {}}}
我是否缺少任何配置选项,或者这根本不可能?
【问题讨论】:
-
我不完全确定我理解你的问题,但你能确认听起来你在问这个测试示例吗:github.com/marshmallow-code/marshmallow/blob/… (test_default_many_symmetry) 对吗?
-
您链接的测试将每个用户序列化为
{"name": "name1"}。我想做的是将每个用户序列化为"name1",特别是对于many=True用例,它应该转储到["King Arthur", "Sir Lancelot"]而不是[{'name': 'King Arthur'}, {'name': 'Sir Lancelot'}]
标签: python nested marshmallow