【问题标题】:python-marshmallow: deserializing nested schema with only one exposed keypython-marshmallow:反序列化嵌套模式,只有一个暴露的键
【发布时间】: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


【解决方案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)

【讨论】:

    猜你喜欢
    • 2011-08-05
    • 1970-01-01
    • 2022-12-14
    • 1970-01-01
    • 2021-11-22
    • 2012-05-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多