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

时间:2019-12-13 10:52:47

标签: python marshmallow marshmallow-sqlalchemy

我使用棉花糖 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]的值?

1 个答案:

答案 0 :(得分:2)

使用Pluck字段:

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