python-marshmallow:仅使用一个公开密钥

时间:2017-10-26 08:38:14

标签: python nested marshmallow

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

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

1 个答案:

答案 0 :(得分:1)

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

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)