18

Schema 我想要一个带有以下输出 json的 Marshmallow -

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

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

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

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

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

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

4

4 回答 4

22

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

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

但是data_key效果很好:

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

    _time = fields.Number(data_key="time")
    _id = fields.String(data_key="id")
于 2019-10-16T13:08:26.870 回答
21

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")
于 2017-10-31T16:39:09.653 回答
10

答案在 Marshmallows api reference中有详细记录。

我需要使用dump_to

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

    time = fields.Number(dump_to='_time')
    id = fields.String(dump_to='_id')
于 2017-06-08T13:27:31.760 回答
2

您可以在返回序列化对象之前覆盖该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,但是,您可能必须将要修改的字段硬编码为类的一部分,这可能不灵活,具体取决于您的用例。

于 2017-06-08T11:27:52.763 回答