如何在不同的nam下序列化棉花糖场

2024-05-23 19:25:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我想要一个棉花糖Schema,输出json-

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

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

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

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

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

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


Tags: idjsonfieldsdata序列化timeschemamore
3条回答

答案在棉花糖中有很好的记载。

我需要使用dump_to

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

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

http://marshmallow.readthedocs.io/en/latest/quickstart.html#specifying-attribute-names

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

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

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

Note: This should only be used for very specific use cases such as outputting multiple fields for a single attribute. In most cases, you should use data_key instead.

但是data_key工作得很好:

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

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

相关问题 更多 >