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

前端之家收集整理的这篇文章主要介绍了从’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中的错误还是我的代码不正确?

提前致谢.

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

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

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

aa.refresh_from_db()
原文链接:https://www.f2er.com/python/439382.html

猜你在找的Python相关文章