2

如果我有模式,请使用 Python、Flask 和棉花糖:

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

和一个Parent有方法的类:

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

如何让 MarshmallowParent.getChildren在序列化对象时传递必要的参数,然后填充ParentSchema.children结果?

4

1 回答 1

4

所以解决方案是get_attribute在模式类中添加一个方法,并将参数分配给类的context属性ParentSchema。这改变了 Marshmallow 在构建模式时用于提取类属性的默认行为。

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)
于 2016-10-07T13:45:51.430 回答