如何在marshmallow-sqlalchemy中使用嵌套对象加载

时间:2016-04-18 23:39:48

标签: python sqlalchemy flask-sqlalchemy marshmallow

我正在使用带有烧瓶扩展的marshmallow-sqlalchemy并尝试使用我的ModelSchema类的加载方法。 我有这样的事情:

db = SQLAlchemy()
ma = Marshmallow()

#I'm using Application Factorie
def create_app():
    ...
    db.init_app(app)
    ma.init_app(app)
    ...
    return app


class BaseSchema(ma.ModelSchema):    
    class Meta:
        sqla_session = db.session  

class Parent(db.Model):    
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(45), nullable=False)
    child_id = db.Column(db.Integer, db.ForeignKey("child.id"), nullable=False)
    child = db.relationship("Child")

class ParentSchema(BaseSchema):
    class Meta:
        model = Parent
    child = ma.Nested("ChildSchema")

class Child(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(25), nullable=False)

class ChildSchema(BaseSchema):
    class Meta:
        model = Child

整体工作完美,查询,插入......但是当我尝试在数据库中加载具有现有子项的新父对象时,如:new_parent = ParentSchema().load({'name':'Foo', 'child' : {'id':1,'name':'Bar'} })会返回AttributeError: 'DummySession' object has no attribute 'query'

我做错了什么?

1 个答案:

答案 0 :(得分:6)

我认为你的BaseSchema的Meta类没有被正确地继承。

更改此

class ParentSchema(BaseSchema):
    class Meta:
        model = Parent

到这个

class ParentSchema(BaseSchema):
    class Meta(BaseSchema.Meta):
        model = Parent

参考:https://marshmallow-sqlalchemy.readthedocs.io/en/latest/recipes.html(基础架构I示例)