You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Marshmallow反序列化时如何映射Schema属性为目标键(处理from保留字)

解决Marshmallow中使用Python保留字"from"作为字段的问题

你可以通过Marshmallow的post_load钩子函数,在反序列化完成后修改字典的键,实现将内部字段名_from替换为目标键from:

from marshmallow import Schema, fields, post_load

class TestSchema(Schema):
    _from = fields.Str(
        required=False,
        missing='',
        data_key='from'
    )

    @post_load
    def adjust_from_key(self, data, **kwargs):
        # 将内部字段名"_from"替换为目标键"from"
        if '_from' in data:
            data['from'] = data.pop('_from')
        return data

效果验证

当你调用load方法处理输入数据时:

schema = TestSchema()
result = schema.load({"from": "example@test.com"})
print(result)  # 输出: {"from": "example@test.com"}

如果需要同时处理序列化(将字典中的from转换为符合Schema定义的输出),可以再添加post_dump钩子:

@post_dump
def revert_from_key(self, data, **kwargs):
    if 'from' in data:
        data['_from'] = data.pop('from')
    return data

这样无论反序列化还是序列化,都能在外部数据和内部处理之间完成键的映射,同时规避Python保留字的限制。

内容的提问来源于stack exchange,提问作者Roman Yakubovich

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 22:25:23