Denis Steinman
Denis Steinman

Reputation: 7799

How to parse a property value only in the nested schema?

I use marshmallow to dump my SQLAlchemy entity to JSON as it shown below:

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

The problem is the code above produces JSON with nested objects instead of pure int-list:

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

How to tell marshmallow to parse only value of id property: "children": [1, 2]?

Upvotes: 1

Views: 272

Answers (1)

Jérôme
Jérôme

Reputation: 14714

Use the Pluck field:

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

Upvotes: 2

Related Questions