Search code examples
flask-restfulmarshmallow

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?


Solution

  • 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)