You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Django实现主分类对应子分类展示问题求助

Fix: Show Only Relevant Subcategories Under Each Main Category

The issue here is that your current template loops through all subcategories for every main category. Instead, you need to access the subcategories directly related to each main category. Here's how to fix this step-by-step:

1. Verify Your Model Relationship

First, make sure your Category model has a foreign key linking it to Main_Category. If you haven’t already, add this field (adjust the related name if you prefer):

# models.py
from django.db import models

class Main_Category(models.Model):
    main_category_name = models.CharField(max_length=255)
    # Add any other fields you need

class Category(models.Model):
    category_name = models.CharField(max_length=255)
    # Link each subcategory to a main category
    main_category = models.ForeignKey(
        Main_Category,
        on_delete=models.CASCADE,
        related_name="subcategories"  # Lets us access subs via mainCat.subcategories
    )
    # Add any other fields you need

2. Optimize the View with Prefetching

To avoid performance issues (N+1 database queries), use prefetch_related to load all subcategories along with their main categories in one go:

# views.py
from django.shortcuts import render
from .models import Main_Category

def homePageView(request):
    # Fetch all main categories and prefetch their related subcategories
    main_cat_list = Main_Category.objects.all().prefetch_related('subcategories')
    context = {'main_cat_list': main_cat_list}
    # You no longer need to pass cat_list to the template!
    return render(request, 'index.html', context)

Modify your template to loop through the related subcategories of each main category instead of all subcategories:

<!-- index.html -->
{% for mainCatList in main_cat_list %}
  <li class="subMenu">
    <a>{{ mainCatList.main_category_name }}</a>
    <ul>
      <!-- Loop through the subcategories linked to this main category -->
      {% for subCat in mainCatList.subcategories.all %}
        <li>
          <a href="products.html">
            <i class="icon-chevron-right"></i>{{ subCat.category_name }}
          </a>
        </li>
      {% endfor %}
    </ul>
  </li>
{% endfor %}

If you didn’t set a related_name in your foreign key, Django uses the default format: {{ model_name }}_set. So your inner loop would be:

{% for subCat in mainCatList.category_set.all %}

That’s it! Now each main category will only display its own associated subcategories.

内容的提问来源于stack exchange,提问作者Mahmud Hassan

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 08:23:39