如何仅在嵌套模式中解析属性值?

问题描述 投票:0回答:1

我使用marshmallow将我的SQLAlchemy实体转储到JSON,如下所示:

class EntitySchema(ma.ModelSchema):
    class Meta:
        model = Entity
    children = fields.List(Nested(ChildSchema(only=("id",))))

问题是上面的代码使用嵌套对象而不是纯int-list生成JSON:

{
    ...
    "children": [{"id": 1}, {"id": 2}]
}

如何告诉棉花糖仅分析id属性的值:"children": [1, 2]

python marshmallow marshmallow-sqlalchemy
1个回答
0
投票

使用Pluck字段:

class EntitySchema(ma.ModelSchema):
    class Meta:
        model = Entity
    children = fields.List(fields.Pluck(ChildSchema, "id"))
© www.soinside.com 2019 - 2024. All rights reserved.