Rom*_*cea 21 python sqlalchemy flask flask-sqlalchemy
我有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" ) )
Run Code Online (Sandbox Code Playgroud)
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" ) )
Run Code Online (Sandbox Code Playgroud)
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 )
Run Code Online (Sandbox Code Playgroud)
如果我尝试(在控制台中)通过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'
Run Code Online (Sandbox Code Playgroud)
任何人都可以了解我做错了什么吗?我想几个月前我的代码运行正常,但我最近更新了SQLAlchemy,Flask和Flask-SQLAlchemy,它停了下来.这只是一个侧面项目.
zzz*_*eek 40
这里有点难,因为你正在使用一些未知的基类,如"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" ) )
Run Code Online (Sandbox Code Playgroud)
secondary需要引用一个Table对象,而不是一个映射的类,如果按字符串名称那么它将是"user_roles":
roles = db.relationship( "Role", secondary = "user_roles", \
backref = db.backref( "users" ) )
Run Code Online (Sandbox Code Playgroud)