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

Python 如何以不同的名称序列化棉花糖字段,python,json,python-2.7,marshmallow,Python,Json,Python 2.7,Marshmallow,我想要一个棉花糖模式,具有以下输出json- { "_id": "aae216334c3611e78a3e06148752fd79", "_time": 20.79606056213379, "more_data" : {...} } 棉花糖不会序列化私人成员,所以这是我能得到的最接近的- class ApiSchema(Schema): class Meta: strict = True time = fields.Number() id

我想要一个棉花糖
模式
,具有以下输出json-

{
  "_id": "aae216334c3611e78a3e06148752fd79",
  "_time": 20.79606056213379,
  "more_data" : {...}
}
棉花糖不会序列化私人成员,所以这是我能得到的最接近的-

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

    time = fields.Number()
    id = fields.String()
但我确实需要输出json中的下划线

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

在返回序列化对象之前,可以重写该方法,将下划线前置到选定字段:

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


您也可以在一个单独的自定义方法上使用decorator,而不必重写
dump
,但随后,您可能必须将要修改的字段硬编码为类的一部分,这可能会因您的用例而变得不灵活。

答案在Marshmallows中有很好的说明

我需要使用
dump\u来

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

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

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

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

  _time = fields.Number(attribute="time")
  _id = fields.String(attribute="id")
接受的答案(使用
属性
)对我不起作用,可能是:

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

但是
数据\u键
运行良好:

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

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

棉花糖3.0中的
dump_to
load_from
data_键
替换。注意:
class ApiSchema(Schema):
    class Meta:
        strict = True

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