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

时间:2022-06-29 03:01:52

Am trying to setup a postgresql table that has two foreign keys that point to the same primary key in another table.

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

When I run the script I get the error

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

sqlalchemy.exc.AmbiguousForeignKeysError: Could not determine join condition between parent/child tables on relationship Company.stakeholder - there are multiple foreign key paths linking the tables. Specify the 'foreign_keys' argument, providing a list of those columns which should be counted as containing a foreign key reference to the parent table.

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

That is the exact error in the SQLAlchemy Documentation yet when I replicate what they have offered as a solution the error doesn't go away. What could I be doing wrong?

这是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')

I have seen similar questions here but some of the answers recommend one uses a primaryjoin yet in the documentation it states that you don't need the primaryjoin in this situation.

我在这里看到过类似的问题,但有些答案建议人们在文档中使用了一个主连接,它声明在这种情况下你不需要主连接。

2 个解决方案

#1


34  

Tried removing quotes from the foreign_keys and making them a list. From official documentation on Relationship Configuration: Handling Multiple Join Paths

尝试从foreign_keys中删除引号并将其作为列表。从关系配置的官方文档:处理多个加入路径

Changed in version 0.8: relationship() can resolve ambiguity between foreign key targets on the basis of the foreign_keys argument alone; the primaryjoin argument is no longer needed in this situation.

更改版本0.8:relationship()可以仅根据foreign_keys参数解决外键目标之间的歧义;在这种情况下不再需要primaryjoin参数。


Self-contained code below works with sqlalchemy>=0.9:

下面的自包含代码适用于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()

#2


1  

The latest documentation:

最新文档:

The form of foreign_keys= in the documentation produces a NameError, not sure how it is expected to work when the class hasn't been created yet. With some hacking I was able to succeed with this:

文档中的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')

In other words:

换一种说法:

… foreign_keys='CurrentClass.thing_id')

#1


34  

Tried removing quotes from the foreign_keys and making them a list. From official documentation on Relationship Configuration: Handling Multiple Join Paths

尝试从foreign_keys中删除引号并将其作为列表。从关系配置的官方文档:处理多个加入路径

Changed in version 0.8: relationship() can resolve ambiguity between foreign key targets on the basis of the foreign_keys argument alone; the primaryjoin argument is no longer needed in this situation.

更改版本0.8:relationship()可以仅根据foreign_keys参数解决外键目标之间的歧义;在这种情况下不再需要primaryjoin参数。


Self-contained code below works with sqlalchemy>=0.9:

下面的自包含代码适用于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()

#2


1  

The latest documentation:

最新文档:

The form of foreign_keys= in the documentation produces a NameError, not sure how it is expected to work when the class hasn't been created yet. With some hacking I was able to succeed with this:

文档中的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')

In other words:

换一种说法:

… foreign_keys='CurrentClass.thing_id')