8

我需要创建一个链表的 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 ?

我在这里想念什么?谷歌搜索让我一无所获......:/

4

1 回答 1

13

正如例外所说,您需要remote_side为关系设置关键字。否则 sqlalchemy 无法选择参考方向。

class Node(declarative_base()):
    ...
    prev = relationship(
        'Node',
        uselist=False,
        remote_side=[id],
        backref=backref('next', uselist=False)
    )
于 2012-10-13T18:27:49.210 回答