在Materialized Path树中显示与请求的对象和子对象相关的对象



类别/模型.py

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

class Category(MP_Node):
title = models.CharField(max_length=50)
slug = models.SlugField(unique=True)
node_order_by = ['title']
class Meta:
verbose_name = 'category'
verbose_name_plural = 'categories'
def __str__(self):
return 'Category: {}'.format(self.title)

类别/视图.py

from django.views.generic import DetailView
from .models import Category

class CategoryDetailView(DetailView):
model = Category
context_object_name = 'category'
template_name = 'categories/category_detail.html'
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context["products_in_category"] = self.object.products.filter(active=True)
return context

category_detail.html

.....
{% for p in products_in_category %}

<h2><a href="{{ p.get_absolute_url }}">{{ p.title }}</a></h2>
.....

上面的代码可以很好地显示属于特定类别的产品,但我也可以显示属于其后代的产品。

示例:

shoes
├── sneakers
│   ├── laced sneakers
│   └── non-laced sneakers

如果我在运动鞋的分类页面上,我希望能够看到与系带运动鞋和无系带运动鞋相关的产品。

我的想法是get_context_data可能看起来像这个

def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context["products_in_category"] = self.object.get_descendants().products.filter(active=True)
return context

但不幸的是,这并没有奏效。

我曾考虑使用ListView,但类别页面将有一个描述类别的描述,因此,我认为DetailView将是一个更好的选择。

你们认为什么是最好的方法?

尝试检查此链接,您可以自定义模板https://docs.djangoproject.com/en/3.2/ref/templates/builtins/#regroup

最新更新