Incorrect results when using the `get_ancestors` functions from` django-mptt`

I am developing a project that uses django-mptt, but I get strange results when I use the function get_ancestors. Here is an example.
I have a simple model inherited from 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

And here is the function that works with this model:

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)

I expected to see the following output values:

[<Classifier: aaa>, <Classifier: aa>, <Classifier: a>, <Classifier: root>]
[<Classifier: bbb>, <Classifier: bb>, <Classifier: b>, <Classifier: root>]

But I realized:

[<Classifier: aaa>, <Classifier: bb>, <Classifier: b>, <Classifier: root>]
[<Classifier: bbb>, <Classifier: bb>, <Classifier: b>, <Classifier: root>]

So, as you can see, this function prints the correct list of ancestors for bbbnode, but the wrong ancestors for aaanode. Can you explain to me why this is happening? Is this a bug in django-mpttor is my code incorrect?

Thanks in advance.

+5
source share
1 answer

node , . , b node, a root , , /, .

, aa.insert_at(a, save = True) proccess, a lft= 2 rght= 3, a node lft= 4 rght= 5.

. - refresh_from_db:

aa.refresh_from_db()
+4

All Articles