gpt4 book ai didi

python - SQLAlchemy 中的邻接表关系如何工作?

转载 作者:太空宇宙 更新时间:2023-11-03 15:58:34 24 4
gpt4 key购买 nike

我正在阅读 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 的所有子节点中。

例如,为了实现您链接到的 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()

关于python - SQLAlchemy 中的邻接表关系如何工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40547363/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com