如何解决我可以使用仅在反序列化时可用的 python marshmallow 创建派生字段吗?
我有以下棉花糖架构:
class TimeSeriesSchema(Schema):
timestamp = fields.DateTime(required=True)
# year = fields.Method("get_year_from_timestamp")
# year = fields.Function(lambda obj: obj.timestamp.year)
latitude = fields.Number(allow_none=True)
longitude = fields.Number(allow_none=True)
# def get_year_from_timestamp(self,value):
# return obj.timestamp.year
有没有办法让 year
成为仅在 timeseries
反序列化时才能访问的字段?这两种注释掉的方法不起作用,因为它们仅在序列化时公开 year
。
为了用代码说明,我希望能够做到以下几点:
timeseries_data = {
'timestamp': '2020-12-30T10:00:00','latitude': None,'longitude': None
}
schema = TimeSeriesSchema()
timeseries = schema.load(timeseries_data)
timeseries['year'] = 2020
解决方法
您可以使用后加载方法来实现您想要的-
class TimeSeriesSchema(Schema):
timestamp = fields.DateTime(required=True)
latitude = fields.Number(allow_none=True)
longitude = fields.Number(allow_none=True)
@post_load
def add_year(self,data,**kwargs):
data["year"] = data["timestamp"].year
return data
如果有人试图在转储或加载中指定“年份”,这不会增加任何处理,但允许您添加派生字段。您还可以使用它来序列化为具有 year 属性的自定义 Timeseries 类。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。