Tôi đang phát triển một dự án sử dụng django-mptt, nhưng tôi nhận được kết quả lạ khi sử dụng hàm get_ancestors
. Đây là một ví dụ.
Tôi đã một đã tạo ra một mô hình đơn giản, thừa hưởng từ MPTTModel:Kết quả sai khi sử dụng các hàm get_ancestors` từ `django-mptt`
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
Và đây là những chức năng mà làm việc với mô hình này:
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)
tôi mong đợi để xem các giá trị tiếp theo trên đầu ra:
[<Classifier: aaa>, <Classifier: aa>, <Classifier: a>, <Classifier: root>]
[<Classifier: bbb>, <Classifier: bb>, <Classifier: b>, <Classifier: root>]
Nhưng insted tôi thấy:
[<Classifier: aaa>, <Classifier: bb>, <Classifier: b>, <Classifier: root>]
[<Classifier: bbb>, <Classifier: bb>, <Classifier: b>, <Classifier: root>]
Vì vậy, khi bạn thấy hàm này in danh sách tổ tiên chính xác cho nút bbb
, nhưng tổ tiên sai cho nút aaa
. Bạn có thể giải thích cho tôi tại sao điều này xảy ra không? Đây có phải là lỗi trong số django-mptt
hoặc mã của tôi không chính xác không?
Xin cảm ơn trước.