You need to enable JavaScript to run this app. 如何在Django中实现分类与关联子分类的层级下拉菜单
优惠活动
大模型
产品
解决方案
定价
更多

如何在Django中实现分类与关联子分类的层级下拉菜单

问题解决方案

核心修改点如下:

  1. 视图层预加载关联子分类,避免N+1查询问题
  2. 模板层遍历每个分类关联的子分类渲染下拉项
  3. 修正下拉组件的唯一ID属性,避免bootstrap交互异常

1. 优化views.py查询

class home(View):
    def get(self, request,):
        # 预加载关联的子分类数据,减少数据库查询次数
        category_list = Categories.objects.prefetch_related('subcategories_set').all()
        return render (request, 'home.html', {'category_list': category_list })

2. 修改HTML模板

<ul class="navbar-nav m-auto">
  {% for category in category_list  %}
  <li class="nav-item dropdown">
    <!-- 给每个下拉按钮生成唯一ID,避免冲突 -->
    <a class="nav-link dropdown-toggle category" href="#" id="navbarDropdown-{{ category.id }}" role="button" data-bs-toggle="dropdown" aria-expanded="false">
      {{ category.name }}
    </a>
    <ul class="dropdown-menu" aria-labelledby="navbarDropdown-{{ category.id }}">
      <!-- 遍历当前分类的所有子分类 -->
      {% for subcategory in category.subcategories_set.all %}
      <li><a class="dropdown-item text-white" href="#">{{ subcategory.name }}</a></li>
      {% empty %}
      <!-- 可选:无子分类时展示的提示 -->
      <li><span class="dropdown-item text-muted">暂无子分类</span></li>
      {% endfor %}
    </ul>
  </li>
  {% endfor %}
</ul>

(可选)优化模型反向引用名称

如果你觉得subcategories_set写法不够直观,可以给外键添加related_name参数自定义反向引用名,修改Subcategories模型的外键字段:

class Subcategories(models.Model):
    # 添加related_name参数,后续可直接通过category.subcategories调用子分类
    categories = models.ForeignKey(Categories, on_delete=models.CASCADE, related_name='subcategories')
    name = models.CharField(max_length=200, blank=False)
    joined_date = models.DateTimeField(default=timezone.now,editable=False)
    update_at = models.DateTimeField(auto_now=True)

    def __str__(self):
        return self.name

修改后views.py的预加载语句可改为Categories.objects.prefetch_related('subcategories').all(),模板遍历也可改为{% for subcategory in category.subcategories.all %}。


内容的提问来源于stack exchange,提问作者Shreyash mishra

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.10 11:42:03