[英]SQLAlchemy self-referential many-to-one relationship: example
As I was following the SQLAlchemy documentation on adjacency list relationships , I was able to replicate their Node
example as follows: 当我遵循有关邻接列表关系的SQLAlchemy文档时,我能够如下复制其
Node
示例:
node_tree = Node(data='root', children=[
Node(data='child1'),
Node(data='child2', children=[
Node(data='subchild1'),
Node(data='subchild2'),
]),
Node(data='child3'),
])
However, I was not able to do the same for the many-to-one relationship. 但是,对于多对一关系,我无法做到这一点。 What would an example of this look like?
这个例子看起来像什么?
Working from the example and many-to-one class definition provided at the aforementioned link (only difference is the added remote_side
argument), plus a nice __repr__
for visualization... 从上述链接提供的示例和多对一类定义开始工作(唯一的区别是增加了
remote_side
参数),外加漂亮的__repr__
以便可视化...
class Node(Base):
__tablename__ = 'node'
id = Column(Integer, primary_key=True)
parent_id = Column(Integer, ForeignKey('node.id'))
data = Column(String(50))
parent = relationship("Node", remote_side=[id])
def __repr__(self):
return "Node(data={!r})".format(self.data)
# Create tree.
node_tree = Node(data='root')
child1 = Node(data='child1', parent=node_tree)
child2 = Node(data='child2', parent=node_tree)
subchild1 = Node(data='subchild1', parent=child2)
subchild2 = Node(data='subchild2', parent=child2)
child3 = Node(data='child3', parent=node_tree)
# For viewing the session as it works.
def print_session_state(operation):
print(operation)
print('new: {}'.format(session.new))
print('dirty: {}\n'.format(session.dirty))
# When child2 is added...
session.add(child2)
print_session_state('add child2')
# Roll back.
session.rollback()
print_session_state('rollback')
# When subchild1 is added...
session.add(subchild1)
print_session_state('add subchild1')
The result: 结果:
add child2
new: IdentitySet([Node(data='child2'), Node(data='root')])
dirty: IdentitySet([])
rollback
new: IdentitySet([])
dirty: IdentitySet([])
add subchild1
new: IdentitySet([Node(data='subchild1'), Node(data='child2'), Node(data='root')])
dirty: IdentitySet([])
The first thing you'll notice is that the instantiation isn't as pretty, since the hierarchy is defined from the bottom up this time. 您会注意到的第一件事是实例化并不那么漂亮,因为这次是从下至上定义层次结构的。
Also, the cascading behavior is different. 同样,级联行为也不同。 With the one-to-many relationship, each
Node
was aware of its children (plural) and cascading traveled down the tree. 通过一对多关系,每个
Node
都知道其子 Node
(复数),并且级联沿着树行进。
With many-to-one, each Node
is only aware of its parent (singular) and cascading travels up the tree, such that only those Node
s in the same branch of the tree as the starting point are reached. 在多对一的情况下,每个
Node
仅知道其父节点 (单数),并且级联沿着树行进,因此仅到达树的同一分支中作为起点的那些Node
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.