![](/img/trans.png)
[英]SQLAlchemy: Multiple foreign keys to same table with compound primary key
[英]SQLAlchemy multiple foreign keys in one mapped class to the same primary key
我正在尝试建立一个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
但在文档中就指出,你不需要primaryjoin
在这种情况下。
试图从foreign_keys中删除引号并将它们制成列表。 来自有关Relationship Configuration: Handling Multiple Join Paths
官方文档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()
最新文档:
文档中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')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.