django-mptt似乎要让我发疯。我试图做一些相对简单的事情:我将删除一个节点,并需要合理处理该节点的子节点。换句话说,我想将它们向上移动一级,使它们成为其当前父节点的父节点。
也就是说,如果树看起来像:
Root
|
Grandpa
|
Father
| |
C1 C2
我要删除父级,希望C1和C2成为Grandpa的子级。
这是我使用的代码:
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()
这个方法几乎可行。孩子们将他们的父母报告为“爷爷”:
c1.parent == grandpa # True
Grandpa将C1和C2视为其子节点
c1 in grandpa.children.all() # True
然而,Root否认与这些孩子有任何关系。
c1.get_root() == father # c1's root is father, instead of Root
c1 in root.get_descendants() # False
如何使子元素移动而不破坏其根元素?
Node
继承于MPTTModel
,并让NodeManager
继承于TreeManager
是有帮助的。 - Sam Bobel