我正在开发一个使用 django-mptt 的项目,但是当我使用get_ancestors
函数时会得到奇怪的结果。这是一个例子。
我创建了一个简单的模型,继承自 MPTTModel:
class Classifier(MPTTModel):
title = models.CharField(max_length=255)
parent = TreeForeignKey('self', null = True, blank = True,
related_name = 'children')
def __unicode__(self):
return self.title
这是适用于此模型的功能:
def test_mptt(self):
# Erase all data from table
Classifier.objects.all().delete()
# Create a tree root
root, created = Classifier.objects.get_or_create(title=u'root', parent=None)
# Create 'a' and 'b' nodes whose parent is 'root'
a = Classifier(title = "a")
a.insert_at(root, save = True)
b = Classifier(title = "b")
b.insert_at(root, save = True)
# Create 'aa' and 'bb' nodes whose parents are
# 'a' and 'b' respectively
aa = Classifier(title = "aa")
aa.insert_at(a, save = True)
bb = Classifier(title = "bb")
bb.insert_at(b, save = True)
# Create two more nodes whose parents are 'aa' and 'bb' respectively
aaa = Classifier(title = "aaa")
aaa.insert_at(aa, save = True)
bba = Classifier(title = "bbb")
bba.insert_at(bb, save = True)
# Select from table just created nodes
first = Classifier.objects.get(title = "aaa")
second = Classifier.objects.get(title = "bbb")
# Print lists of selected nodes' ancestors:
print first.get_ancestors(ascending=True, include_self=True)
print second.get_ancestors(ascending=True, include_self=True)
我希望在输出中看到下一个值:
[<Classifier: aaa>, <Classifier: aa>, <Classifier: a>, <Classifier: root>]
[<Classifier: bbb>, <Classifier: bb>, <Classifier: b>, <Classifier: root>]
但是我看到:
[<Classifier: aaa>, <Classifier: bb>, <Classifier: b>, <Classifier: root>]
[<Classifier: bbb>, <Classifier: bb>, <Classifier: b>, <Classifier: root>]
因此,正如您所看到的,此函数打印节点的正确祖先列表bbb
,但打印节点的祖先错误aaa
。你能解释一下为什么会这样吗?这是一个错误django-mptt
还是我的代码不正确?
提前致谢。