python - SQLAlchemy一对一,在每个表中存储外键?

标签 python python-3.x sqlalchemy

笼子代码和邓氏号码之间存在一对一的关系。

我已经建立了看起来像这样的关系,我在每个相应的表上存储了一个外键。

class Cage(Base):
    __tablename__ = 'DimCage'

    id = Column(Integer, primary_key=True)
    cage = Column(String(8), unique=True, nullable=False)
    duns_id = Column(Integer, ForeignKey('DimDuns.id'))

    duns = relationship('Duns', uselist=False, back_populates='cage')


class Duns(Base):
    __tablename__ = 'DimDuns'

    id = Column(Integer, primary_key=True)
    duns = Column(String(10), unique=True, nullable=False)
    dunsInt = Column(Integer, unique=True, nullable=False)
    cage_id = Column(Integer, ForeignKey('DimCage.id'))

    cage = relationship('Cage', uselist=False, back_populates='duns')

当我创建表时出现以下错误,如何设置外键以便在两个表上保留引用?

sqlalchemy.exc.AmbiguousForeignKeysError: Can't determine join between 'DimCage' and 'DimDuns'; tables have more than one foreign key constraint relationship between them. Please specify the 'onclause' of this join explicitly.

并且在处理上述异常的过程中,发生了另一个异常:

sqlalchemy.exc.AmbiguousForeignKeysError: Could not determine join condition between parent/child tables on relationship Cage.duns - 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.

最佳答案

我相信您只需要存储一个外键即可建立一对一的关系。
请参阅https://docs.sqlalchemy.org/en/13/orm/basic_relationships.html#one-to-one

您不应以这种方式丢失任何数据访问权限。如果您从 Cage 中删除 duns_id 列,您现在可以通过 cage.duns.id 而不是 cage.duns_id< 访问 ID/.

关于python - SQLAlchemy一对一,在每个表中存储外键?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56691341/

相关文章:

python - 如何显示 openerp 错误信息

python - 如何连接到 boto3 中的区域

python - 尝试微调 NER 的 ReformerModelWithLMHead (google/reformer-enwik8) 时出错

python - 从列表/数组字典中迭代实例化类的最佳方法是什么?

python - 如何在另一个异步循环中使用异步循环

python-3.x - 从 Pandas 数据框列中删除一个字符

python-3.x - 如何使用带有预定义分割折叠的显式验证集?

postgresql - SQLAlchemy 表达式语言问题

sqlalchemy - 使用 python-asyncio 数据库时如何获取最后插入 ID

python - 结果 : Failure Exception: AttributeError: 'Engine' object has no attribute 'execute' Azure Functions