数据库
首页 > 数据库> > sqlalchemy.exc.NoForeignKeysError; AmbiguousForeignKeysError; Could not determine join condition bet

sqlalchemy.exc.NoForeignKeysError; AmbiguousForeignKeysError; Could not determine join condition bet

作者:互联网

刚接触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)

 

标签:__,sqlalchemy,join,exc,Column,db,Integer,table,id
来源: https://www.cnblogs.com/HoD7/p/15481650.html