3

假设我有这些模型:

class Category(MP_Node):
    name = models.CharField(max_length=30)

class Item(models.Model):
    category = models.ForeignKey(Category)

我想找到Item属于给定任何后代Category的所有 s 。

通常我会写category.item_set,但这只是Item属于层次结构的给定级别。

使用树须教程中的示例树,如果一个项目属于“笔记本电脑内存”,我将如何找到属于“笔记本电脑内存”是这些后代之一的后代“计算机硬件”的所有项目?

4

2 回答 2

2

我刚刚遇到了同样的问题,并想出了如何去做(在get_queryseta 的函数中考虑它ListView):

category = Category.objects.filter(slug=self.kwargs['category']).get()
descendants = list(category.get_descendants().all())
return self.model.objects.select_related('category').filter(category__in=descendants+[category, ])

我想出的另一个选择是使用带有“OR”的过滤器:

from django.db.models import Q

category = Category.objects.filter(slug=self.kwargs['category']).get()
descendants = list(category.get_descendants().all())
return self.model.objects.select_related('category').filter(Q(category__in=category.get_descendants()) | Q(category=category))
于 2015-10-17T01:47:14.313 回答
2

我查看了 treebeard 代码以了解它如何获取节点的后代。我们可以应用与相关字段查找相同的过滤器。

paramcat = Category.objects.get(id=1) # how you actually get the category will depend on your application
#all items associated with this category OR its descendants:
items = Item.objects.filter(category__tree_id=paramcat.tree_id, category__lft__range=(paramcat.lft,paramcat.rgt-1))

我认为使用像 get_descendants 这样的中间调用会导致每个后代有一个查询,并将所有后代加载到内存中。它首先破坏了使用树须的目的

我有兴趣查看基于此代码的自定义查找,我不知道该怎么做......

于 2018-04-05T01:06:54.410 回答