marshmallow - 序列化时如何将架构属性映射到另一个键?

2023-12-25

我需要创建一个与给定规范一致的棉花糖模式,其中我无法更改键名称。其中一个关键是 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)?


Use dump_to/load_from(棉花糖2)或data_key (棉花糖3 https://marshmallow.readthedocs.io/en/stable/quickstart.html#specifying-serialization-deserialization-keys):

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)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

marshmallow - 序列化时如何将架构属性映射到另一个键? 的相关文章

随机推荐