
本教程将详细介绍如何使用marshmallow序列化库,将模型实例中的字符串id字段(例如`parent_id`)转换为嵌套的json对象结构,如`{"id": "123-345"}`。文章将探讨两种主要方法:利用`fields.nested`结合`pre_dump`钩子进行预处理,以及通过`fields.method`直接定义序列化逻辑。此外,还将简要提及自定义字段的实现,旨在帮助开发者根据具体需求选择最合适的序列化策略,确保数据输出格式的灵活性与准确性。
在构建API时,我们经常需要对数据进行序列化,以符合特定的JSON输出格式。有时,模型中的某个字段可能只是一个简单的字符串(例如,一个关联对象的ID),但在API响应中,我们希望它以一个嵌套对象的形式呈现,例如{"id": "value"}。本文将以一个具体的场景为例,演示如何在Marshmallow中实现这种转换。
假设我们有一个User模型,其中包含name字段和一个parent字段。parent字段在模型实例中存储为一个字符串,代表父级用户的ID。我们期望在序列化后,parent字段能够以{"id": "..."}的格式输出。
期望的输出格式:
{
  "name": "John",
  "parent": {"id": "123-345"}
}首先,定义一个简单的Python类来模拟我们的模型实例:
import marshmallow as m
from marshmallow import Schema, fields, pre_dump
# 模拟模型类
class User:
    def __init__(self, name, parent_id=None):
        self.name = name
        self.parent = parent_id # parent_id 在模型中是一个字符串或None
# 创建一个用户实例
user_instance = User("John Doe", "123-345")
user_without_parent = User("Jane Smith")这是解决此问题的一种巧妙且有效的方法,它利用了Marshmallow的fields.Nested字段和pre_dump钩子。
class IdSchema(Schema):
    id = fields.String(required=True)
    @pre_dump
    def wrap(self, data, **_):
        """
        在IdSchema处理数据之前,将原始字符串ID包装成字典。
        当fields.Nested(IdSchema)接收到'123-345'这样的字符串时,
        这个字符串会作为data参数传递给pre_dump。
        """
        if data is None:
            return None # 处理parent为None的情况
        return {"id": data}
class UserSchemaNestedPreDump(Schema):
    name = fields.String(required=True)
    # parent字段使用IdSchema进行嵌套序列化
    parent = fields.Nested(IdSchema, allow_none=True) # 允许parent字段为None
# 序列化并查看结果
schema_pre_dump = UserSchemaNestedPreDump()
result_with_parent = schema_pre_dump.dump(user_instance)
print("--- Solution 1 (Nested with pre_dump) ---")
print("With parent:", result_with_parent)
result_without_parent = schema_pre_dump.dump(user_without_parent)
print("Without parent:", result_without_parent)输出:
--- Solution 1 (Nested with pre_dump) ---
With parent: {'name': 'John Doe', 'parent': {'id': '123-345'}}
Without parent: {'name': 'Jane Smith', 'parent': None}fields.Method提供了一种更直接的方式来定义字段的序列化逻辑,它允许你指定一个方法来处理特定字段的输出。
class UserSchemaMethodField(Schema):
    name = fields.String(required=True)
    # parent字段通过get_parent_id_wrapped方法进行序列化
    parent = fields.Method("get_parent_id_wrapped", allow_none=True)
    def get_parent_id_wrapped(self, obj):
        """
        根据模型实例的parent属性,返回包装后的字典。
        obj参数是当前的User模型实例。
        """
        if obj.parent is None:
            return None
        return {"id": obj.parent}
# 序列化并查看结果
schema_method_field = UserSchemaMethodField()
result_with_parent_method = schema_method_field.dump(user_instance)
print("\n--- Solution 2 (Method Field) ---")
print("With parent:", result_with_parent_method)
result_without_parent_method = schema_method_field.dump(user_without_parent)
print("Without parent:", result_without_parent_method)输出:
--- Solution 2 (Method Field) ---
With parent: {'name': 'John Doe', 'parent': {'id': '123-345'}}
Without parent: {'name': 'Jane Smith', 'parent': None}对于更复杂的或需要在多个地方复用的序列化逻辑,创建自定义字段是最佳选择。
继承marshmallow.fields.Field并重写其_serialize方法。_serialize方法负责将原始值转换为序列化后的值。
class WrappedIdField(fields.Field):
    def _serialize(self, value, attr, obj, **kwargs):
        """
        将原始值(value)包装成{"id": value}的格式。
        value是模型实例中对应属性的原始值。
        """
        if value is None:
            return None
        return {"id": str(value)} # 确保value是字符串类型
class UserSchemaCustomField(Schema):
    name = fields.String(required=True)
    # parent字段使用自定义的WrappedIdField
    parent = WrappedIdField(attribute="parent", allow_none=True) # attribute指定模型实例的哪个属性被序列化
# 序列化并查看结果
schema_custom_field = UserSchemaCustomField()
result_with_parent_custom = schema_custom_field.dump(user_instance)
print("\n--- Solution 3 (Custom Field) ---")
print("With parent:", result_with_parent_custom)
result_without_parent_custom = schema_custom_field.dump(user_without_parent)
print("Without parent:", result_without_parent_custom)输出:
--- Solution 3 (Custom Field) ---
With parent: {'name': 'John Doe', 'parent': {'id': '123-345'}}
Without parent: {'name': 'Jane Smith', 'parent': None}Marshmallow提供了多种灵活的方式来处理数据序列化,即使是看似简单的字符串包装成嵌套对象的需求,也有多种实现路径。
在实际开发中,开发者应根据具体场景的复杂性、复用需求和团队偏好,选择最合适的Marshmallow序列化策略。无论选择哪种方法,清晰的代码结构和对None值的妥善处理都是确保API健壮性的关键。
以上就是Marshmallow 教程:实现字符串字段到嵌套字典的优雅序列化的详细内容,更多请关注php中文网其它相关文章!
                        
                        每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
                Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号