sqlalchemy.exc.InvalidRequestError: Multiple classes found for path “Students” in the registry of this declarative base. Please use a fully module-qualified path.已解决
在flask中使用orm,尝试进行连接查询,总是报错
我是这样写的
from apps import db
# 班级表
class Classes(db.Model):
__table_args__ = {"extend_existing" : True}
__tablename__ = "classes"
id = db.Column(db.Integer,primary_key=True)
name = db.Column(db.String(20),nullable=False,unique=True)
relate_student = db.relationship("Students", backref='relate_class', lazy='dynamic')
# 学生表
class Students(db.Model):
__table_args__ = {"extend_existing" : True}
__tablename__ = "students"
id = db.Column(db.Integer,primary_key=True)
name = db.Column(db.String(40),nullable=False)
cls_id = db.Column(db.Integer,db.ForeignKey("classes.id")) # 注意要写成(表名.字段名)
进行调用测试连接查询
@app.route('/')
def hello_world():
stu = Students.query.filter(Students.name == '张三').first()
print(stu.relate_class.name)
return "ok"
然后直接访问http://127.0.0.1:5000/,就出现如下错误:
sqlalchemy.exc.InvalidRequestError: Multiple classes found for path “Students” in the registry of this declarative base. Please use a fully module-qualified path.我用有道词典翻译了一下错误,大概是这个意思:
invalidrequesterror:在这个声明性基的注册表中为路径“Students”找到了多个类。 请使用完全模块限定的路径。
然后我尝试在网上找了很多解决方案,最终还是没能解决掉,怀疑可能是sqlalchemy版本问题,然后把sqlalchemy卸载重装了一下,但是还是没有解决掉
最后我灵机一动,将代码尝试改成如下:
from apps import db
# 学生表
class Students(db.Model):
__table_args__ = {"extend_existing" : True}
__tablename__ = "students"
id = db.Column(db.Integer,primary_key=True)
name = db.Column(db.String(40),nullable=False)
cls_id = db.Column(db.Integer,db.ForeignKey("classes.id")) # 注意要写成(表名.字段名)
# 班级表
class Classes(db.Model):
__table_args__ = {"extend_existing" : True}
__tablename__ = "classes"
id = db.Column(db.Integer,primary_key=True)
name = db.Column(db.String(20),nullable=False,unique=True)
relate_student = db.relationship(Students, backref='relate_class', lazy='dynamic')