如何用Django treebeard获取节点的所有后代,包括它自己?

bfrts1fy  于 2023-08-08  发布在  Go
关注(0)|答案(1)|浏览(108)

我有一个Category模型,它用Django treebeard扩展了MP_Node,如下所示:

# "models.py"

from django.db import models
from treebeard.mp_tree import MP_Node

class Category(MP_Node):
    name = models.CharField(max_length=50)
    node_order_by = ('name',)

    def __str__(self):
        return self.name

字符串
然后,我可以使用Django treebeard通过get_descendants()获取不包括其自身的类别的所有后代,如下所示:

categories = Category.objects.get(name="Food").get_descendants()
print(categories)
# <MP_NodeQuerySet [<Category: Meat>, <Category: Fish>]>


但是,当我尝试使用Django treebeard通过get_descendants(include_self=True)获取一个类别的所有后代时,我得到了如下所示的错误:

categories = Category.objects.get(name="Food").get_descendants(include_self=True)
print(categories) # Error


TypeError:get_descendants()获取了意外的关键字参数“include_self”
实际上,我可以使用Django mptt获得一个类别的所有后代,包括get_descendants(include_self=True)本身,如下所示。* 我将Django mptt切换到Django treebeard,因为Django mptt是未维护的,并给出一些错误:

categories = Category.objects.get(name="Food").get_descendants(include_self=True)
print(categories)
# <TreeQuerySet [<Category: Food>, <Category: Meat>, <Category: Fish>]>


那么,我怎样才能用Django treebeard得到一个类别的所有后代,包括它自己呢?

pxy2qtax

pxy2qtax1#

您可以覆盖get_descendants()并将include_self=False作为第二个参数添加到它,使用Django treebeard,如下所示。* 你可以看到原始的get_descendants():

from django.db import models
from treebeard.mp_tree import MP_Node, get_result_class

class Category(MP_Node):
    name = models.CharField(max_length=50)
    node_order_by = ('name',)

    def get_descendants(self, include_self=False):
        if include_self:
            return self.__class__.get_tree(self)
        if self.is_leaf():
            return get_result_class(self.__class__).objects.none()
        return self.__class__.get_tree(self).exclude(pk=self.pk)

    def __str__(self):
        return self.name

字符串
然后,你可以通过Django treebeard得到一个类别的所有后代,包括它自己,如下所示:

categories = Category.objects.get(name="Food").get_descendants(include_self=True)
print(categories)
# <MP_NodeQuerySet [<Category: Food>, <Category: Meat>, <Category: Fish>]>


另外,你可以通过get_tree(parent=None)使用Django treebeard获取一个类别的所有后代,包括它自己,如下所示。* 你需要使用一个对象来使用get_tree(parent=None)

categories = Category.objects.all()[2].get_tree(Category.objects.get(name="Food"))
print(categories)
# <MP_NodeQuerySet [<Category: Food>, <Category: Meat>, <Category: Fish>]>

categories = Category.objects.first().get_tree(Category.objects.get(name="Food"))
print(categories)
# <MP_NodeQuerySet [<Category: Food>, <Category: Meat>, <Category: Fish>]>

categories = Category.objects.last().get_tree(Category.objects.get(name="Food"))
print(categories)
# <MP_NodeQuerySet [<Category: Food>, <Category: Meat>, <Category: Fish>]>

相关问题