web-dev-qa-db-ja.com

Flask-SQLAlchemy-モデルには属性 'foreign_keys'がありません

Flask-SQLalchemyで作成された3つのモデルがあります: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 )
_

(コンソールで)User.query.all()を介してすべてのユーザーを取得しようとすると、_AttributeError: 'NoneType' object has no attribute 'all'_が表示され、再試行すると、次のような別のエラーが発生します。

_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'
_

誰かが私が間違っているのは正確には何であるかを明らかにすることができますか?このコードは数か月前に正常に実行されていたと思いますが、SQLAlchemy、FlaskおよびFlask-SQLAlchemyを最近更新したところ、停止しました。これは単なる副次的なプロジェクトです。

21
Romeo Mihalcea

「ActiveRecord」などの未知の基本クラスを使用しているため、ここでは少し難しいです。ただし、その「二次」引数が間違っているように見えます。

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は、マップされたクラスではなく、Tableオブジェクトを参照する必要があります。文字列名では、"user_roles"

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