Django基于自关联分类模型的树形菜单如何在模板中循环渲染
层级分类前端渲染实现步骤
1. 视图层数据准备
基于现有自关联分类模型,核心筛选有效分类数据,提前预取关联子分类避免数据库重复查询。
对应函数视图代码示例:
from django.shortcuts import render from .models import newCatagory, products def render_nav_with_cats(request): # 获取所有顶级分类(无父级、状态为Show的分类) top_level_cats = newCatagory.objects.filter( parent__isnull=True, status=1 ).prefetch_related("newcatagory_set").all() return render(request, "你的模板文件路径.html", { "nav_cat_list": top_level_cats })
说明:由于当前定义的
parent外键未设置related_name,Django默认生成的反向关联访问名是模型名小写加_set,即newcatagory_set,用于访问某分类下的所有直接子分类。使用prefetch_related预取关联子分类,可将原本的N+1次数据库查询压缩为2次,避免页面加载卡顿。
2. 模板层结构渲染
替换原硬编码占位的HTML片段,通过双层循环匹配现有导航结构:
{% for top_cat in nav_cat_list %} <li> <a href="/category/{{ top_cat.id }}/">{{ top_cat.cat_name }}</a> {# 筛选当前顶级分类下状态为Show的二级子分类 #} {% with second_cats=top_cat.newcatagory_set.filter.status=1 %} {% if second_cats %} <ul class="sub-menu"> {% for second_cat in second_cats %} <li><a href="/category/{{ second_cat.id }}/">{{ second_cat.cat_name }}</a></li> {% endfor %} </ul> {% endif %} {% endwith %} </li> {% endfor %}
3. 实用优化建议
- 给
parent外键补充related_name配置,提升代码可读性,修改示例:
配置后后续代码可直接用parent = models.ForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name="sub_categories")top_cat.sub_categories代替生硬的top_cat.newcatagory_set访问子分类。 - 若需支持超过两级的深层分类结构,可编写自定义模板递归标签实现无限层级渲染,当前常规两级导航场景上述代码完全满足需求。
- 所有分类、产品的查询逻辑都必须增加
status=1的筛选条件,避免把Hide状态的无效内容渲染到前端。 - 分类详情页关联产品获取逻辑:递归收集当前分类及所有下属子分类的ID,批量筛选关联的在售产品:
# 传入目标分类ID current_cat = newCatagory.objects.get(id=target_cat_id) collect_cat_ids = [current_cat.id] # 递归收集所有子分类ID def collect_sub_ids(cat): for sub in cat.sub_categories.filter(status=1): collect_cat_ids.append(sub.id) collect_sub_ids(sub) collect_sub_ids(current_cat) # 批量获取关联产品 cat_related_products = products.objects.filter( sub_cat_id__in=collect_cat_ids, status=1 )
内容的提问来源于stack exchange,提问作者San San
相关产品推荐
相关产品推荐

