gpt4 book ai didi

django-mptt - 使用 django-mptt 创建子记录

转载 作者:行者123 更新时间:2023-12-04 04:57:02 27 4
gpt4 key购买 nike

我已经成功完成了 django-mptt 教程。我无法弄清楚如何做的是创建一个 child 的 child 。

child 的 child ,我的意思是更深的第三级。看下面的例子,我想创建 1.3.1, 1.3.2, 1.3.1.1

1.0 Product Z
1.1 Product A
1.2 Product B
1.3 Product P
1.3.1 Product X
1.3.1.1 Product O
1.3.2 Product Y
2.0 Product H

doco我找到了 insert_node但不明白它足以让它工作。我还在 code comments 中找到了一些东西(第 317 行)关于 insert_node那说:
NOTE: This is a low-level method; it does NOT respect ``MPTTMeta.order_insertion_by``.
In most cases you should just set the node's parent and let mptt call this during save.

我应该使用“insert_node”还是有更好的方法?如果应该使用'insert_node',那么您能否提供一个使用示例?

最佳答案

我承认,这可能有点令人困惑。但正如你所读到的 here , order_insertion_by field 应该只在您追求标准插入行为之类的东西时使用,例如按字母顺序排列的树等,因为它会触发额外的 db 查询。

但是,如果要在树中的特定点插入节点,则必须使用
TreeManager.insert_node MPTTModel.insert_at ,后者是调用第一个的便捷方法。

因此,根据您的示例,这会导致以下三个选项来添加新的 1.3.3 产品 Q 作为 1.3 产品 P 的最后一个子项:

new_node = ProductNode(name='1.3.3 Product Q')

parent = ProductNode.objects.get(name='1.3 Product P')


# With `order_insertion_by`

new_node.parent = parent
new_node.save()


# With `TreeManager.insert_node`

ProductNode.objects.insert_node(new_node, parent, position='last-child', save=True)


# With `MPTTModel.insert_at`

new_node.insert_at(parent, position='last-child', save=True)

关于django-mptt - 使用 django-mptt 创建子记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16621106/

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