You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Django MPTT:如何仅筛选所点击子分类关联的服务

解决Django-MPTT分类仅显示当前分类关联服务的问题

问题根源

你的ServiceByCategoryListView里的get_queryset方法存在两个关键问题:

  • 强制仅查找顶级分类(filter(parent=None)),导致子分类无法被正确匹配
  • 使用get_descendants(include_self=True)获取了当前分类的所有后代节点,因此会返回整个分支下的所有服务

修改方案

直接调整ServiceByCategoryListView的get_queryset方法,移除多余的后代查询逻辑,仅匹配当前点击的分类本身:

# views.py 修改后的 ServiceByCategoryListView
class ServiceByCategoryListView(ListView):
    model = Service
    context_object_name = 'services'
    template_name = 'main/service_list.html'

    def get_queryset(self):
        # 直接通过slug获取对应分类,不再限制父级为空
        self.category = Category.objects.get(slug=self.kwargs['slug'])
        # 仅筛选关联当前分类的服务,而非整个分支
        queryset = Service.objects.filter(category=self.category)
        return queryset

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['name'] = self.category
        return context

改动说明

  • 移除filter(parent=None):无论顶级分类还是子分类,都能通过slug正确定位到对应的Category对象
  • 替换category__in=branch_categories为category=self.category:直接关联当前分类,不再包含其子分类的关联服务

修改完成后,点击任意分类(顶级或子分类),都会仅显示该分类本身关联的服务,完全满足需求。

内容的提问来源于stack exchange,提问作者Pavel S

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.10 02:27:12