以下是一个示例代码,用于解决“不是所有的子类别都显示在永久链接中”的问题:
from django.shortcuts import render
from django.views.generic import ListView
from django.db.models import Q
from .models import Category, SubCategory
class CategoryListView(ListView):
model = Category
template_name = 'category_list.html'
context_object_name = 'categories'
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
categories = Category.objects.all()
context['categories'] = categories
return context
class SubCategoryListView(ListView):
model = SubCategory
template_name = 'subcategory_list.html'
context_object_name = 'subcategories'
def get_queryset(self):
queryset = super().get_queryset()
category_slug = self.kwargs.get('category_slug')
queryset = queryset.filter(category__slug=category_slug)
return queryset
在上述示例代码中,我们定义了两个视图类:CategoryListView
和SubCategoryListView
。CategoryListView
用于显示所有的类别,而SubCategoryListView
用于显示特定类别下的子类别。
在SubCategoryListView
中,我们重写了get_queryset
方法,通过category_slug
参数过滤子类别的查询集。这里假设你的子类别模型有一个外键字段category
,用于关联父类别。
接下来,在你的URL配置中,你可以将这两个视图类分别与对应的URL模式绑定:
from django.urls import path
from .views import CategoryListView, SubCategoryListView
urlpatterns = [
path('categories/', CategoryListView.as_view(), name='category_list'),
path('categories//', SubCategoryListView.as_view(), name='subcategory_list'),
]
在上述示例中,我们将CategoryListView
绑定到/categories/
路径,将SubCategoryListView
绑定到/categories/
路径,其中
用于接收父类别的slug作为参数。
最后,你可以创建对应的模板文件category_list.html
和subcategory_list.html
,用于渲染类别和子类别的列表。在模板文件中,你可以使用categories
和subcategories
变量来访问查询到的类别和子类别数据。
这样,当你访问/categories/
时,将显示所有的类别;当你访问/categories/
时,将只显示特定类别下的子类别。
下一篇:不是所有地图元素都会更改类名