【问题标题】:How to use load with nested objects in marshmallow-sqlalchemy如何在 marshmallow-sqlalchemy 中对嵌套对象使用负载
【发布时间】:2016-08-10 21:44:57
【问题描述】:

我正在使用带有烧瓶扩展的 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'

我做错了什么?

【问题讨论】:

    标签: python sqlalchemy flask-sqlalchemy marshmallow


    【解决方案1】:

    我认为您的 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 示例)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-11-22
      • 1970-01-01
      • 2021-04-19
      • 2017-08-23
      • 2019-01-16
      • 1970-01-01
      • 2020-05-21
      • 2019-06-25
      相关资源
      最近更新 更多