刚接触SQLAlchemy, 被这except折腾了一会.
网上很多都说是名字打错了, 其实还有其他情况会触发此类except.
不知是否是该ORM特性, 需要建立关系的表(model)需要继承自同一基类. 否则会找不到对应的ModelName(__tablename__).
如:
from sqlalchemy.ext.declarative import declarative_base from run import db # 这里db由SQLAlchemy(app)得到, 详见flask Base = declarative_base() a_2_b = db.Table( "a_2_b", Base.metadata, db.Column("a_id", db.Integer, db.ForeignKey("a_table.id")), db.Column("b_id", db.Integer, db.ForeignKey("b_table.id")) ) class a(db.Model): __tablename__ = "a_table" id = db.Column(db.Integer, primary_key=True) members = db.relationship("a", backref="b_list", secondary=a_2_b) class b(db.Model): __tablename__ = "b_table" id = db.Column(db.Integer, primary_key=True)
此时会抛出相关异常.
解决方法为将需要建立关系的model继承自同一基类, 即:
class a(Base): __tablename__ = "a_table" id = db.Column(db.Integer, primary_key=True) members = db.relationship("a", backref="b_list", secondary=a_2_b) class b(Base): __tablename__ = "b_table" id = db.Column(db.Integer, primary_key=True)