Tintin
Tintin

Reputation: 567

How to pass a parameter in a Marshmallow schema

Using Python, Flask and marshmallow, if I have a schema:

class ParentSchema(Schema):
    id = fields.Int(dump_only=True)
    children = fields.Nested('ChildSchema', dump_only=True)

and a class Parent which has a method:

class Parent():
    getChildren(self, params):
        pass

How do I get Marshmallow to pass the necessary parameters to Parent.getChildren when serialising the object and then populate ParentSchema.children with the results?

Upvotes: 2

Views: 4681

Answers (1)

Tintin
Tintin

Reputation: 567

So the solution is to add a get_attribute method to the schema class and to assign the parameters to the context attribute of the ParentSchema class. This alters the default behaviour that Marshmallow uses to extract class attributes when building the schema.

class ParentSchema(Schema):
    id = fields.Int(dump_only=True)
    children = fields.Nested('ChildSchema', dump_only=True)

    def get_attribute(self, key, obj, default):
        if key == 'children':
            return obj.getChildren(self.context['params'])
        else:
            return getattr(obj, key, default)

Upvotes: 4

Related Questions