gpt4 book ai didi

python - django-mptt:如何成功移动节点

转载 作者:太空狗 更新时间:2023-10-30 00:57:58 26 4
gpt4 key购买 nike

django-mptt 似乎下定决心要让我失去理智。我正在尝试做一些相对简单的事情:我要删除一个节点,并且需要对该节点的子节点做一些合理的事情。即,我想将它们提升一个级别,以便它们成为当前父级的父级的子级。

也就是说,如果树看起来像:

 Root
|
Grandpa
|
Father
| |
C1 C2

我要删除父亲,并希望 C1 和 C2 成为爷爷的 child 。

这是我使用的代码:

class Node(models.Model):
first_name = models.CharField(max_length=80, blank=True)
parent = models.ForeignKey('self', null=True, blank=True, related_name='children')

def reparent_children(self, parent):
print "Reparenting"
for child in self.get_children():
print "Working on", child.first_name, "to parent", parent.email
parent = Node.objects.get(id=parent.id)
child.move_to(parent, 'last-child')
child.save()

所以我会调用:

father.reparent_children(grandpa)
father.parent = None
father.save()

这几乎行得通。 children 报告他们的 parent 是爷爷:

c1.parent == grandpa  # True

爷爷把C1和C2算在它的 child 中

c1 in grandpa.children.all()   # True

但是,Root 与这些 child 断绝关系。

c1.get_root() == father  # c1's root is father, instead of Root

c1 in root.get_descendants() # False

如何让 children 移动并且他们的根不被破坏?

最佳答案

内部 lftrght 值将在您第一次保存 child 时更改(即 reparent_children 方法的最后一行)。 save() 不会更新您周围可能存在的实例。我认为一个安全的方法是每次都从数据库中重新获取它们,如下所示:

def reparent_children(self, parent):
print "Reparenting"
for child in self.get_children():
print "Working on", child.first_name, "to parent", parent.email
parent = Node.objects.get(id=parent.id)
current_child = Node.objects.get(id = child.id)
current_child.move_to(parent, 'last-child')
current_child.save()

我有 similar problems不久前,这种方法解决了我的问题。

关于python - django-mptt:如何成功移动节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3040214/

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