gpt4 book ai didi

python - Flask-SQLAlchemy - 模型没有属性 'foreign_keys'

转载 作者:IT老高 更新时间:2023-10-28 20:51:59 26 4
gpt4 key购买 nike

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

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

user.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,但它停止了。这只是一个附带项目。

最佳答案

这里有点困难,因为您使用了一些未知的基类,例如“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" ) )

关于python - Flask-SQLAlchemy - 模型没有属性 'foreign_keys',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19205290/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com