pythonmarshmallowmarshmallow-sqlalchemy

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]?


Solution

  • Use the Pluck field:

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