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

2021/10/29 19:09:41

本文主要是介绍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.exc.NoForeignKeysError; AmbiguousForeignKeysError; Could not determine join condition bet的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程