一尘不染

SQLAlchemy将一个映射的类中的多个外键映射到同一主键

python

我正在尝试建立一个PostgreSQL表,该表具有两个指向另一个表中相同主键的外键。

运行脚本时出现错误

sqlalchemy.exc.AmbiguousForeignKeysError:无法确定关系Company.stakeholder的父/子表之间的联接条件-
有多个链接表的外键路径。指定“ foreign_keys”参数,提供这些列的列表,这些列应被视为包含对父表的外键引用。

那是SQLAlchemy文档中的确切错误,但是当我复制他们作为解决方案提供的内容时,该错误不会消失。我可能做错了什么?

#The business case here is that a company can be a stakeholder in another company.
class Company(Base):
    __tablename__ = 'company'
    id = Column(Integer, primary_key=True)
    name = Column(String(50), nullable=False)

class Stakeholder(Base):
    __tablename__ = 'stakeholder'
    id = Column(Integer, primary_key=True)
    company_id = Column(Integer, ForeignKey('company.id'), nullable=False)
    stakeholder_id = Column(Integer, ForeignKey('company.id'), nullable=False)
    company = relationship("Company", foreign_keys='company_id')
    stakeholder = relationship("Company", foreign_keys='stakeholder_id')

我在这里看到了类似的问题,但是一些答案建议primaryjoin在文档中使用“a”表示状态下您不需要primaryjoin


阅读 149

收藏
2020-12-20

共1个答案

一尘不染

尝试从foreign_keys中删除引号并将它们制成列表。从官方文档开始Relationship Configuration: Handling Multiple Join Paths

在版本0.8中进行了更改:relationship()可以foreign_keys仅基于参数就可以解决外键目标之间的歧义;primaryjoin在这种情况下,不再需要该参数。


以下自包含的代码适用于sqlalchemy>=0.9

from sqlalchemy import create_engine, Column, Integer, String, ForeignKey
from sqlalchemy.orm import relationship, scoped_session, sessionmaker
from sqlalchemy.ext.declarative import declarative_base

engine = create_engine(u'sqlite:///:memory:', echo=True)
session = scoped_session(sessionmaker(bind=engine))
Base = declarative_base()

#The business case here is that a company can be a stakeholder in another company.
class Company(Base):
    __tablename__ = 'company'
    id = Column(Integer, primary_key=True)
    name = Column(String(50), nullable=False)

class Stakeholder(Base):
    __tablename__ = 'stakeholder'
    id = Column(Integer, primary_key=True)
    company_id = Column(Integer, ForeignKey('company.id'), nullable=False)
    stakeholder_id = Column(Integer, ForeignKey('company.id'), nullable=False)
    company = relationship("Company", foreign_keys=[company_id])
    stakeholder = relationship("Company", foreign_keys=[stakeholder_id])

Base.metadata.create_all(engine)

# simple query test
q1 = session.query(Company).all()
q2 = session.query(Stakeholder).all()
2020-12-20