繁体   English   中英

如何以不同的名称序列化棉花糖字段

[英]How to serialize a Marshmallow field under a different name

我想要一个带有以下输出 json 的棉花糖Schema -

{
  "_id": "aae216334c3611e78a3e06148752fd79",
  "_time": 20.79606056213379,
  "more_data" : {...}
}

Marshmallow 不会序列化私有成员,所以这是我所能得到的尽可能接近 -

class ApiSchema(Schema):
    class Meta:
        strict = True

    time = fields.Number()
    id = fields.String()

但我确实需要输出 json 中的下划线。

有没有办法告诉 Marshmallow 使用不同的名称序列化字段?

接受的答案(使用attribute )对我不起作用,可能是因为

注意:这应该仅用于非常特定的用例,例如为单个属性输出多个字段。 在大多数情况下,您应该改用 data_key。

然而data_key工作得很好:

class ApiSchema(Schema):
    class Meta:
        strict = True

    _time = fields.Number(data_key="time")
    _id = fields.String(data_key="id")

https://marshmallow.readthedocs.io/en/2.x-line/quickstart.html#specifying-attribute-names

尽管文档是针对版本 2 的,但从 3.5.1 开始,这似乎仍然有效。 稳定版 3 文档将没有此示例。

class ApiSchema(Schema):
  class Meta:
      strict = True

  _time = fields.Number(attribute="time")
  _id = fields.String(attribute="id")

答案在 Marshmallows api 参考中有详细记录

我需要使用dump_to

class ApiSchema(Schema):
    class Meta:
        strict = True

    time = fields.Number(dump_to='_time')
    id = fields.String(dump_to='_id')

您可以覆盖dump方法返回序列化对象之前,前面加上下划线来选定字段:

class ApiSchema(Schema):
    class Meta:
        strict = True

    time = fields.Number()
    id = fields.String()

    def dump(self, *args, **kwargs):
        special = kwargs.pop('special', None)
        _partial = super(ApiSchema, self).dump(*args, **kwargs)
        if special is not None and all(f in _partial for f in special):
            for field in special:
                _partial['_{}'.format(field)] = _partial.pop(field)
        return _partial

api_schema = ApiSchema(...)
result = api_schema.dump(obj, special=('id', 'time'))

您还可以在单​​独的自定义方法上使用post_dump装饰器,而不必覆盖dump ,但是,您可能必须将要修改的字段硬编码为类的一部分,这可能不灵活,具体取决于您的用例。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM