[英]How does the Adjacency List Relationships works in SQLAlchemy?
我正在阅读SQLAlchemy文档,但对给定的示例感到困惑:
class Node(Base):
__tablename__ = 'node'
id = Column(Integer, primary_key=True)
parent_id = Column(Integer, ForeignKey('node.id'))
data = Column(String(50))
children = relationship("Node")
我知道一个 Node 对象可以通过这个类定义有很多孩子。 我的理解是在创建和保存一个Node对象时,会在数据库中插入一条记录(id, parent_id, data),我知道默认会生成id
,但是parent_id
是怎么生成的呢? 我在我的项目中尝试了类似的用法,但parent_id
保持None
。
parent_id
并不是真正生成的,它是使用对象之间的实际关系分配的。 这就是说sqlalchemy
会将parent_id
正确保存到关系Node.children
所有子Node.children
。
例如,为了实现sqlalchemy
的文档中记录的关系图,您链接到:
root --+---> child1
+---> child2 --+--> subchild1
| +--> subchild2
+---> child3
您可以通过以下方式编写代码:
root = Node(
data='root',
# @NOTE: all Node under this children will have `parent_id` point to the `id` of this (root) Node
children=[
Node(data='child1'),
Node(data='child2',
children=[
Node(data='subchild1'),
Node(data='subchild2'),
]),
Node(data='child3')
]
)
session.add(root) # this will also add all the other nodes in the graph
session.commit()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.