Flask-SQLAlchemy - model has no attribute 'foreign_keys'

冷暖自知 提交于 2020-01-22 13:26:32

问题


I have 3 models created with Flask-SQLalchemy: User, Role, UserRole

user.py:

class Role( ActiveRecord, db.Model ):

    __tablename__ = "roles"

    #   Schema
    id = db.Column( db.Integer, primary_key = True )
    name = db.Column( db.String( 24 ), unique = True )
    description = db.Column( db.String( 90 ) )

    users = db.relationship( "User", secondary = "UserRole", \
        backref = db.backref( "roles" ) )

role.py:

class User( db.Model, ActiveRecord ):

    __tablename__ = "users"

    #   Schema
    id = db.Column( db.Integer, primary_key = True )
    email = db.Column( db.String( 90 ), unique = True )
    password = db.Column( db.String( 64 ) )

    #   Relations
    roles = db.relationship( "Role", secondary = "UserRole", \
        backref = db.backref( "users" ) )

user_role.py:

class UserRole( ActiveRecord, db.Model ):

    __tablename__ = "user_roles"

    #   Schema
    user_id = db.Column( db.Integer, db.ForeignKey( 'users.id' ), primary_key = True )
    role_id = db.Column( db.Integer, db.ForeignKey( 'roles.id' ), primary_key = True )

If I try (in the console) to get all users via User.query.all() I get AttributeError: 'NoneType' object has no attribute 'all' and if I try again I get another error saying:

sqlalchemy.exc.InvalidRequestError: One or more mappers failed to initialize - can't proceed with initialization of other mappers.  Original exception was: type object 'UserRole' has no attribute 'foreign_keys'

Can anyone shed a light on what is it exactly that I'm doing wrong? I think I had this code running ok a few months ago, but I updated SQLAlchemy, Flask and Flask-SQLAlchemy recently and it stopped. It's just a side project.


回答1:


it's a little tough here because you are using some unknown base classes like "ActiveRecord" and such. However, it looks pretty much like that "secondary" argument is wrong:

class User( db.Model, ActiveRecord ):

    __tablename__ = "users"

    #   Schema
    id = db.Column( db.Integer, primary_key = True )
    email = db.Column( db.String( 90 ), unique = True )
    password = db.Column( db.String( 64 ) )

    #   Relations
    roles = db.relationship( "Role", secondary = "UserRole", \
        backref = db.backref( "users" ) )

secondary needs to refer to a Table object, not a mapped class, if by string name then it would be "user_roles":

    roles = db.relationship( "Role", secondary = "user_roles", \
        backref = db.backref( "users" ) )


来源:https://stackoverflow.com/questions/19205290/flask-sqlalchemy-model-has-no-attribute-foreign-keys

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!