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



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

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

棉花糖不序列化私人成员,所以这是我所能得到的尽可能接近 -

class ApiSchema(Schema):
    class Meta:
        strict = True
    time = fields.Number()
    id = fields.String()

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

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

接受的答案(使用 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")

答案在棉花糖 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 ,但是,您可能必须将要修改的字段硬编码为类的一部分,这可能不灵活,具体取决于您的用例。

最新更新