笼子代码和邓氏号码之间存在一对一的关系。
我已经建立了看起来像这样的关系,我在每个相应的表上存储了一个外键。
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/