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

标签 python 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)?

最佳答案

使用 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)

关于python - marshmallow - 序列化时如何将架构属性映射到另一个键?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51727441/

相关文章:

python - 导入错误 : cannot import name log

python 以一定的概率生成一个数字的随机整数

python - 使用 Marshmallow 反序列化强制执行严格的字段。日期格式

python - pydantic无法区分整数和字符串

python - 从棉花糖中的嵌套键加载

python - 在 Python 中自定义验证器的正则表达式

python - Python 脚本中的 Maya 崩溃

python - 从 element.ResultSet 中提取项目

python-3.x - 使用 marshmallow 指定一个或多个字段

python - 编写 Python POO。棉花糖或原生 Python。创建类的最佳方式是什么?