我正在尝试使用django-mptt,但运气不佳。这是 svn 最新的 Python2.5、windows、sqlite3、Django 1.2pre、django-mptt。
编码:
模型:
class Node(models.Model):
name = models.CharField(max_length=20, blank=True)
parent = models.ForeignKey('self', null=True, blank=True, related_name='children')
def __unicode__(self):
return self.name
mptt.register(Node)
设置:
nodes = []
for i in range(15):
n = Node(name='node'+str(i))
n.save()
nodes.append(n)
nodes[0].move_to(None)
nodes[0].save()
for n in range(1,15):
nodes[n].move_to(nodes[(n-1)/2],'last-child')
nodes[n].save()
这应该创建一棵树,每个非叶节点都有一个根和两个子节点。
现在乐趣开始了:
>>> nodes[0].children.all()
[<Node: node1>, <Node: node2>]
>>> nodes[0].get_descendants()
[]
>>> nodes[0].get_descendants(True)
[<Node: node0>, <Node: node2>]
>>> for n in nodes:
... print n, n.get_ancestors()
...
node0 []
node1 [<Node: node0>]
node2 [<Node: node0>]
node3 [<Node: node0>, <Node: node2>]
node4 [<Node: node0>, <Node: node2>]
node5 [<Node: node0>, <Node: node2>]
node6 [<Node: node0>, <Node: node2>]
node7 [<Node: node0>, <Node: node2>, <Node: node6>]
node8 [<Node: node0>, <Node: node2>, <Node: node6>]
node9 [<Node: node0>, <Node: node2>, <Node: node6>]
node10 [<Node: node0>, <Node: node2>, <Node: node6>]
node11 [<Node: node0>, <Node: node2>, <Node: node6>]
node12 [<Node: node0>, <Node: node2>, <Node: node6>]
node13 [<Node: node0>, <Node: node2>, <Node: node6>]
node14 [<Node: node0>, <Node: node2>, <Node: node6>]
为什么很多祖宗都错了?例如,节点 10 应该有祖先,(0,1,10)
我做错了什么还是 django-mptt 中有错误?