我需要创建链接列表的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 ?
我在这里缺少什么?谷歌搜索让我无处可寻......:/
答案 0 :(得分:9)
异常表示您需要为关系设置remote_side
关键字。否则sqlalchemy无法选择参考方向。
class Node(declarative_base()):
...
prev = relationship(
'Node',
uselist=False,
remote_side=[id],
backref=backref('next', uselist=False)
)