我有3个使用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 )
如果我尝试(在控制台中)通过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,它停了下来。这只是一个辅助项目。
答案 0 :(得分:31)
这里有点难,因为你正在使用一些未知的基类,如“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" ) )