SQLAlchemy将多个外键在一个映射类中转换为相同的主键

时间:2014-03-12 15:16:16

标签: python postgresql sqlalchemy

我试图设置一个postgresql表,它有两个指向另一个表中相同主键的外键。

当我运行脚本时,我收到错误

  

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

这是SQLAlchemy Documentation中的确切错误,但当我复制他们提供的解决方案时,错误并没有消失。我能做错什么?

#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')

我在这里看到过类似的问题,但some of the answers建议人们使用primaryjoin,但在文档中说明在这种情况下你不需要primaryjoin

2 个答案:

答案 0 :(得分:39)

尝试从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()

答案 1 :(得分:2)

最新文档:

文档中foreign_keys=的形式产生了一个NameError,不确定在尚未创建类时它应该如何工作。有了一些黑客攻击,我就能成功:

company_id = Column(Integer, ForeignKey('company.id'), nullable=False)
company = relationship("Company", foreign_keys='Stakeholder.company_id')

stakeholder_id = Column(Integer, ForeignKey('company.id'), nullable=False)
stakeholder = relationship("Company",
                            foreign_keys='Stakeholder.stakeholder_id')

换句话说:

… foreign_keys='CurrentClass.thing_id')