【问题标题】:Can I create a derived field using python marshmallow that only available when deserialized?我可以使用仅在反序列化时可用的 python marshmallow 创建派生字段吗?
【发布时间】:2021-03-25 13:33:50
【问题描述】:

我有以下棉花糖架构:

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

【问题讨论】:

    标签: python marshmallow


    【解决方案1】:

    您可以使用后加载方法来实现您想要的-

    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 类。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-12-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-11-09
      相关资源
      最近更新 更多