【问题标题】:How to pass a parameter in a Marshmallow schema如何在 Marshmallow 模式中传递参数
【发布时间】:2016-10-09 00:52:06
【问题描述】:

如果我有架构,请使用 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

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

【问题讨论】:

    标签: flask-restful marshmallow


    【解决方案1】:

    所以解决方案是在schema类中添加get_attribute方法,并将参数分配给ParentSchema类的context属性。这会改变 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)
    

    【讨论】:

      猜你喜欢
      • 2021-10-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-15
      • 1970-01-01
      • 2014-01-16
      • 1970-01-01
      相关资源
      最近更新 更多