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)
推荐阅读
- riscv - 有没有开源的 tilelink 验证基础设施?
- scala - ActorTestKit 的关闭方法无法正常工作
- c++ - 将数组的元素传递给c ++中的函数
- javascript - ES5 Javascript 通过数组中的对象映射,然后按组更改对象键
- php - 尝试使用 if !isset 来显示没有表单的结果
- rabbitmq - RabbitMq 日志填充 {{badmatch,{error,access_refused}},占用磁盘空间
- apache-spark - 如何将集群 Spark 中的所有内核用于一个进程?
- go - 为什么我的程序在添加 time.sleep 时会挂起?
- angularjs - 如何使用 URL 中的片段实现 Graph SSO?
- c++ - 在数组程序错误中查找回文字符串的数量