从’django-mptt`使用`get_ancestors`函数时出现错误的结果

我正在开发一个使用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)

我希望在输出上看到下一个值:

[

但是我看到了:

[

因此,当您看到此函数为bbb节点打印正确的祖先列表,但aaa节点的错误祖先.你能解释一下为什么会这样吗?这是django-mptt中的错误还是我的代码不正确?

提前致谢.

最佳答案
将节点插入树中时,会导致整个树发生更改.因此,当您插入b节点时,您的a和根节点会在数据库中更改,但您的变量不会更新并保持包含旧的左/右值,这些值用于构建正确的树结构.

在你的情况下,当行aa.insert_at(a,save = True)在proccess中时,你的变量包含一个lft = 2和rght = 3的旧实例,而在数据库中,一个节点包含lft = 4和rght = 5.

在插入新项目之前,您需要获取父项的新实例.最简单的方法是运行refresh_from_db:

aa.refresh_from_db()

相关文章

我最近重新拾起了计算机视觉,借助Python的opencv还有face_r...
说到Pooling,相信学习过CNN的朋友们都不会感到陌生。Poolin...
记得大一学Python的时候,有一个题目是判断一个数是否是复数...
文章目录 3 直方图Histogramplot1. 基本直方图的绘制 Basic ...
文章目录 5 小提琴图Violinplot1. 基础小提琴图绘制 Basic v...
文章目录 4 核密度图Densityplot1. 基础核密度图绘制 Basic ...