【问题标题】:SQLAlchemy multiple foreign keys in one mapped class to the same primary keySQLAlchemy 一个映射类中的多个外键到同一个主键
【发布时间】:2014-04-16 20:17:27
【问题描述】:

我正在尝试设置一个 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

【问题讨论】:

    标签: python postgresql sqlalchemy


    【解决方案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()
    

    【讨论】:

    • 这样做之后,我得到了错误sqlalchemy.exc.AmbiguousForeignKeysError: Can't determine join between 'company' and 'stakeholder'; tables have more than one foreign key constraint relationship between them. Please specify the 'onclause' of this join explicitly.
    • 你有什么版本的 sqlalchemy?
    • 收到SQLAlchemy==0.9.1
    • 这取决于你是否需要它。您是否需要从Stakeholder 导航到Company?在任何情况下都要小心,因为您不能为两种关系使用相同的名称 backref,所以如果您这样做,我会输入类似 company = relationship("Company", foreign_keys=[company_id], backref="holders")stakeholder = relationship("Company", foreign_keys=[stakeholder_id], backref="holdings") 的名称。
    • 如果我们总是只传递一个元素列表,为什么 sqlalchemy 使用 foreign_keys 参数作为列表?当我们使用外键作为二元素列表时,是否存在某些情况?
    【解决方案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')
    

    【讨论】:

    • 文档已经更新,没有错别字。文档中的方法甚至在创建类之前就可以工作
    • 查看接受的答案。只要给foreign_keys=[stakeholder_id]
    猜你喜欢
    • 2022-01-16
    • 2011-10-12
    • 2014-05-31
    • 2018-05-05
    • 2014-06-15
    • 1970-01-01
    • 1970-01-01
    • 2011-08-10
    相关资源
    最近更新 更多