【问题标题】:How do you add a child node to a parent in an adjacency list in sqlalchemy?如何在 sqlalchemy 的邻接列表中将子节点添加到父节点?
【发布时间】:2014-02-26 09:29:18
【问题描述】:

我在看下面的例子。我的程序设置类似,但没有 backref。我想要一对多的关系。孩子们不需要认识他们的父母。我只是对“node = TreeNode('rootnode')”这一行感到困惑,这不是每次执行程序时都会运行并可能创建重复项吗?

如何添加没有父 backref 的子节点?

我看到例如以下内容

node = TreeNode('rootnode')
TreeNode('node1', parent=node)

node1 是用名称“node1”创建的,它的父节点是单独传递的。父在子关系中定义为

backref("parent", remote_side=id)

我不需要孩子认识父母,只要父母认识孩子。您如何建立这种关系,让父母了解孩子?

http://docs.sqlalchemy.org/en/latest/_modules/examples/adjacency_list/adjacency_list.html

【问题讨论】:

    标签: python sqlalchemy


    【解决方案1】:
    rootnode = TreeNode('rootnode')
    # assign "children" attribute straight away:
    node1 = TreeNode('node1', 
        children=[TreeNode('node1.child1'), TreeNode('node1.child2')]
        )
    # or just manipulate as any regular list
    rootnode.children.append(node1)
    

    我链接到parent 的示例已经知道children,因为定义了relationship 子级:

    children = relationship("TreeNode", # NOTE: now each TreeNode has "children"
                        # ...
                        backref=backref("parent", remote_side=id), # this line allows children to link to "parent"
                        # ...
                    )
    

    因此

    【讨论】:

    • 非常感谢。效果很好,
    猜你喜欢
    • 1970-01-01
    • 2020-08-25
    • 1970-01-01
    • 2017-12-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-31
    • 1970-01-01
    相关资源
    最近更新 更多