5

我试图通过仅从嵌套项中获取一个字段来将嵌套对象列表序列化为标量值。而不是[{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: {}}}

我是否缺少任何配置选项,或者这根本不可能?

4

1 回答 1

3

对于遇到相同问题的任何人,这是我目前使用的解决方法:

class MySchema(Schema):
    key = fields.String(required=True)

    def load(self, data, *args):
        data = [
            {'key': item} if isinstance(item, str) else item
            for item in data
        ]
        return super().load(data, *args)


class ParentSchema(Schema):
    items = fields.Nested(MySchema, only='key', many=True)
于 2017-10-28T08:45:29.020 回答