27

我有 3 个使用 Flask-SQLalchemy 创建的模型:用户、角色、用户角色

角色.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" ) )

用户.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" ) )

用户角色.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()I get获取所有用户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,但它停止了。这只是一个附带项目。

4

1 回答 1

55

这里有点困难,因为您使用了一些未知的基类,例如“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" ) )
于 2013-10-09T01:27:35.913 回答