我正在尝试使用SQLAlchemy的joined inheritance结构来完成以下one-to-one relationship:Box
和Item
都是Element
和{{1 }}有一个Box
。
类定义如下:
Item
当我尝试实例化class Element(Base):
__tablename__ = 'element'
id = Column(Integer, primary_key=True)
el_type = Column(String)
__mapper_args__ = dict(
polymorphic_identity='element',
polymorphic_on=el_type,
)
class Box(Element):
# Joined table inheritance: Element.
__tablename__ = 'box'
id = Column(Integer, ForeignKey('element.id'), primary_key=True)
__mapper_args__ = dict(polymorphic_identity='box')
# One-to-one relationship: Item.
item = relationship('Item',
back_populates='box', uselist=False)
def __init__(self, item_name=None):
self.item = Item(item_name)
class Item(Element):
# Joined table inheritance: Element.
__tablename__ = 'item'
id = Column(Integer, ForeignKey('element.id'), primary_key=True)
__mapper_args__ = dict(polymorphic_identity='item')
# One-to-one relationship: Box.
box_id = Column(Integer, ForeignKey('box.id'))
box = relationship('Box',
back_populates='item')
name = Column(String)
def __init__(self, name):
self.name = name
时,我得到:
b = Box('rock')
现在,我进入了SQLAlchemy的page on this issue(我可能会添加很棒的文档),但是我不确定如何弥合他们的示例与我的情况之间的鸿沟。我认为这可能会解决问题:
sqlalchemy.exc.AmbiguousForeignKeysError: Could not determine join condition between parent/child tables on relationship Box.item - 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.
...但是我遇到了同样的错误。
我在做什么错了?
我现在尝试使用ForeignKeyConstraint
构造,以便更明确地向SQLAlchemy描述所需的行为;无济于事:
class Item(Element):
# ...
box = relationship('Box',
back_populates='item', foreign_keys=[id, box_id])
# ...
一个简单的class Box(Element):
# ...
id = Column(Integer, primary_key=True)
# ...
ForeignKeyConstraint([id], ['element.id'])
# ...
class Item(Element):
# ...
id = Column(Integer, primary_key=True)
# ...
# One-to-one relationship: Box.
box_id = Column(Integer)
box = relationship('Box',
back_populates='item')
ForeignKeyConstraint([id, box_id], ['element.id', 'box.id'])
# ...
被扔给我(没有描述)。鉴于SQLAlchemy在产生有意义的错误消息方面拥有良好的记录,这是否表明这是意料之外的情况?