Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

'Marshmallow' object has no attribute 'ModelSchema'

Everything looks fine from the documentation but it still gives me this error when I'm running the app:

  File "main.py", line 21, in <module>
    class UserSchema(ma.ModelSchema):
AttributeError: 'Marshmallow' object has no attribute 'ModelSchema'

Everything is imported correctly. The DB is committed. The behavior is the same on pipenv and venv.

Am I missing something?

from flask import Flask, jsonify
from flask_sqlalchemy import SQLAlchemy 
from flask_marshmallow import Marshmallow

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///marshmallowjson.db'

db  = SQLAlchemy(app)
ma = Marshmallow(app)

class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(50))

class Item(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    item_name = db.Column(db.String(50))
    user_id = db.Column(db.Integer, db.ForeignKey('user.id'))
    user = db.relationship('User', backref='items')

class UserSchema(ma.ModelSchema):
    class Meta:
        model = User 
        
class ItemSchema(ma.ModelSchema):
    class Meta:
        model = Item

@app.route('/')
def index():
    users = User.query.all()
    user_schema = UserSchema(many=True)
    output = user_schema.dump(users).data
    return jsonify({'user': output})

if __name__ == '__main__':
    app.run(debug=True)
like image 821
Art Chaz Avatar asked Sep 18 '19 03:09

Art Chaz


3 Answers

Conf.py

from flask_sqlalchemy import SQLAlchemy
from flask_marshmallow import Marshmallow

db = SQLAlchemy(app)
ma = Marshmallow(app) 

# flask-marshmallow<0.12.0

class UserSchema(ma.ModelSchema):
      class Meta:
            model = User

# flask-marshmallow>=0.12.0 (recommended)

from conf import ma
class UserSchema(ma.SQLAlchemyAutoSchema):
      class Meta:
            model = User
            load_instance = True

# flask-marshmallow>=0.12.0 (not recommended)

from marshmallow_sqlalchemy import ModelSchema
class UserSchema(ModelSchema):
      class Meta:
            model = User
            sql_session = db.session
like image 72
Bacar Pereira Avatar answered Oct 01 '22 12:10

Bacar Pereira


I hate when it happens, but i got the answer immediately after posting...

Was installed only flask-marshmallow, but

pipenv install marshmallow-sqlalchemy

needed to add to work with SQLAlchemy. Whole code stays the same.

Maybe it will help someone... Now i got a different issue but that's another story.

like image 29
Art Chaz Avatar answered Oct 01 '22 12:10

Art Chaz


Cool ! it got deprecated in the newer version .

class UserSchema(ma.ModelSchema):
class Meta:
    model = User 

change that to

class UserSchema(ma.SQLAlchemyAutoSchema):
class Meta:
    model=User
    load_instance=True

this should work well now!!

like image 44
Pavan elisetty Avatar answered Oct 01 '22 12:10

Pavan elisetty