首页 > 解决方案 > marshmallow - 序列化时如何将模式属性映射到另一个键?

问题描述

我需要创建一个与给定规范一致的棉花糖模式,其中我无法更改键名。一个关键是 Python 中的保留关键字“from”。

class TemporalExtentSchema(Schema):
    from = fields.String(required=True)
    to = fields.String(required=True)

这在 Python 中当然是不允许的,所以我需要这样写:

class TemporalExtentSchema(Schema):
    t_from = fields.String(required=True)
    to = fields.String(required=True)

我想要的是:

{
    "from": "2018-01-01",
    "to": "2018-01-10"
}

序列化时是否可以将实例属性映射到另一个键(t_from -> from)?

标签: pythonmarshmallow

解决方案


使用dump_to/ load_from(marshmallow 2) 或data_key( marshmallow 3 ):

class TemporalExtentSchema(Schema):
    # Marshmallow 2
    t_from = fields.String(required=True, dump_to='from', load_from='from')
    # Marshmallow 3
    t_from = fields.String(required=True, data_key='from')
    to = fields.String(required=True)

推荐阅读