【问题标题】:Finding Descendant Item Sets查找后代项目集
【发布时间】:2015-02-21 01:17:57
【问题描述】:
假设我有这些模型:
class Category(MP_Node):
name = models.CharField(max_length=30)
class Item(models.Model):
category = models.ForeignKey(Category)
我想找到属于给定Category 的任何descendant 的所有Items。
通常我会写category.item_set,但这只是属于给定层次结构级别的Items。
使用treebeard tutorial 中的示例树,如果一个项目属于“笔记本电脑内存”,我如何找到属于“计算机硬件”后代的所有项目,其中“笔记本电脑内存”是这些后代之一?
【问题讨论】:
标签:
django-models
adjacency-list
django-treebeard
【解决方案1】:
我刚刚遇到了同样的问题并想出了解决办法(在函数 get_queryset 的 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))
【解决方案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 之类的中间调用将导致每个后代进行一次查询,并将所有后代加载到内存中。它首先破坏了使用树须的目的
我有兴趣查看基于此代码的自定义查找,但我不知道该怎么做...