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

SQLAlchemy-Marshmallow如何将嵌套Schema对象序列化为值列表

解决方案

Marshmallow原生支持自定义序列化规则,这里给两种最常用的实现方案:

方案1:使用fields.Pluck(最简方案)

Pluck字段是专门用于提取嵌套对象指定字段、直接生成值列表的场景,只需要修改RecipeSchema中的ingredients字段定义即可:

class RecipeSchema(Schema):
    class Meta:
        ordered = True

    id = fields.Int()
    title = fields.Str()
    desc = fields.Str()
    # 替换原Nested字段为Pluck
    ingredients = fields.Pluck('IngredientSchema', 'name', many=True)

修改后直接执行RecipeSchema().dump(recipe)就能得到你预期的输出效果。

方案2:自定义序列化方法(灵活扩展适用复杂逻辑)

如果后续需要对嵌套字段做额外处理(比如过滤、格式化值等),可以用fields.Method自定义序列化逻辑:

class RecipeSchema(Schema):
    class Meta:
        ordered = True

    id = fields.Int()
    title = fields.Str()
    desc = fields.Str()
    ingredients = fields.Method("get_ingredient_names")

    # 自定义方法参数obj就是当前序列化的Recipe实例
    def get_ingredient_names(self, obj):
        return [ing.name for ing in obj.ingredients]

如果需要全局统一处理同类序列化逻辑,也可以自定义字段类型继承fields.Field重写_serialize方法实现。

内容的提问来源于stack exchange,提问作者Jake Thomson

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 17:15:03