SQLAlchemy中的一对一自我关系
问题内容:
我需要创建链表的SQLAlchemy版本。它实际上比这更复杂,但归结为:
我在课堂上需要 一对一,自我参照,双向关系 。每个元素只能有一个单亲或根本没有一个,最多可以有一个孩子。
我简化了课程,因此看起来像这样:
class Node(declarative_base()):
__tablename__ = 'nodes'
id = Column(Integer, Sequence('nodes_id_seq'), primary_key=True, autoincrement=True)
value = Column(Integer)
prev_node_id = Column(Integer, ForeignKey('nodes.id'))
next = relationship('Node', uselist=False, backref=backref('prev', uselist=False))
但是,当我尝试创建一个时,会引发异常:
>>> Node()
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "<string>", line 2, in __init__
File "sqlalchemy\orm\instrumentation.py", line 309, in _new_state_if_none
state = self._state_constructor(instance, self)
[...]
File "sqlalchemy\orm\properties.py", line 1418, in _generate_backref
self._add_reverse_property(self.back_populates)
File "sqlalchemy\orm\properties.py", line 871, in _add_reverse_property
% (other, self, self.direction))
ArgumentError: Node.next and back-reference Node.prev are both of the same direction <symbol 'ONETOMANY>. Did you mean to set remote_side on the many-to-one side ?
我在这里想念什么?谷歌搜索让我无处可去…:/
问题答案:
作为例外,您需要remote_side
为关系设置关键字。否则,sqlalchemy无法选择参考方向。
class Node(declarative_base()):
...
prev = relationship(
'Node',
uselist=False,
remote_side=[id],
backref=backref('next', uselist=False)
)