Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use load with nested objects in marshmallow-sqlalchemy

I'm using marshmallow-sqlalchemy with flask extension and trying to use the load method of my ModelSchema class. I have something like this:

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

Overall works perfectly, queries, inserts... But when I try to load a new parent object with a existing child in data base like: new_parent = ParentSchema().load({'name':'Foo', 'child' : {'id':1,'name':'Bar'} }) returns it AttributeError: 'DummySession' object has no attribute 'query'.

What am i doing wrong?

like image 842
Jair Perrut Avatar asked Apr 18 '16 23:04

Jair Perrut


1 Answers

I THINK that your BaseSchema's Meta class isn't being inherited properly.

Change this

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

to this

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

Reference: https://marshmallow-sqlalchemy.readthedocs.io/en/latest/recipes.html (Base Schema I example)

like image 130
whoiswes Avatar answered Nov 10 '22 08:11

whoiswes