SQLAlchemy中的一对一自我关系

ewi*_*ino 5 python 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))
Run Code Online (Sandbox Code Playgroud)

但是,当我尝试创建一个时,它会引发异常:

>>> 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 ?
Run Code Online (Sandbox Code Playgroud)

我在这里错过了什么?谷歌搜索让我无处可寻......:/

小智 11

例外情况说你需要remote_side为关系设置关键字.否则sqlalchemy无法选择参考方向.

class Node(declarative_base()):
    ...
    prev = relationship(
        'Node',
        uselist=False,
        remote_side=[id],
        backref=backref('next', uselist=False)
    )
Run Code Online (Sandbox Code Playgroud)

  • 或者,您可以使用带引号的表达式稍后加载(例如“ Node.id”而不是Node.id) (2认同)