邻接列表关系如何在SQLAlchemy中起作用?

时间:2016-11-11 11:46:48

标签: 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

1 个答案:

答案 0 :(得分:1)

parent_id并非真正生成,而是使用对象之间的实际关系进行分配。这就是说sqlalchemyparent_idNode.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()
相关问题