类别/模型.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)
类别/views.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 将是一个更好的选择。
你们认为最好的方法是什么?