2010-06-14 2 views
5

django-mptt는 나를 정신 박약니다. 나는 상대적으로 간단한 것을하려고 노력하고있다 : 나는 노드를 삭제할 것이고, 노드의 자식들과 합리적인 것을 할 필요가있다. 즉, 나는 그들을 한 수준 위로 움직여 그들이 현재 부모의 부모의 자녀가되도록하고 싶다. 내가 아버지를 삭제하는거야, 할아버지의 자녀로 C1 및 C2 싶습니다django-mptt : 노드를 성공적으로 이동하는 방법

Root 
    | 
Grandpa 
    | 
Father 
| | 
C1 C2 

: 나무가 보이는 경우이다

.

는 여기에 내가 사용하고 코드입니다 :

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 

할아버지는 아이들

c1 in grandpa.children.all() # True 

들 C1 및 C2를 계산하지만, 루트 아이들을 부인하는.

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

c1 in root.get_descendants() # False 

어떻게 아이들을 이동시키고 그 루트가 손상되지 않습니까?

+1

를 원한다면 당신은 child.move_node (부모)와 child.parent = 부모를 대체 할 수 있습니까? – mawimawi

+0

이 경우 노드를 실제로 삭제하지 않고 보관합니다. 나는 나무에서 그것을 제거하고 싶습니다. 당신은 좋은 지적을 가지고 있습니다, 나는 실제로 나무에서 그것을 제거하지 않습니다. – Parand

+0

부모를 None으로 설정하고 저장하는 것은 실제로 트리에서 노드를 제거하는 방법입니다 (mptt 테스트 사례에 따라). – Parand

답변

6

내부 lftrght 값은 처음으로 자녀를 저장하면 변경됩니다 (예 : 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가 있고, 그 방법은 내 문제를 해결했다.

+4

Dominic, 나는이 방법으로 끝났습니다. * 장고 -mptt로 끝나도 작동합니다. 끊임없이 내 자신의 온건함에 의문을 제기했다.실제로 문제를 해결했는지 또는 다른 곳에 숨겨 놓았는지 여부는 알 수 없습니다. – Parand

1

이 라이브러리는 지난 며칠 동안 정말 혼란 스러웠습니다. move_to는 내가 원하는 것을 실제로하지 않는 것 같아요. 내 나무는 계속 동기화되지 않고 있습니다. 나는 속도와 비 전통적 성을 희생하면서 자신감이있는 해결책을 찾았다.

관리자 방법을 중심으로 회전합니다 partial_rebuildhere.

def delete_node(self): 
    if not self.parent: 
     print("Should not delete root node, confusing behavior follows") 
     return 
    tree_id = self.tree_id 
    parent = self.parent 

    for child in self.get_children(): 
     child.parent = parent 
     child.save() 

    self.delete() 
    Node.objects.partial_rebuild(tree_id) 

는 "father.parent = 없음"노드를 삭제하는 올바른 방법 없다는 것을 확신이

관련 문제