Django实现主分类对应子分类展示问题求助
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)
3. Update the Template to Show Related Subcategories
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 %}
Note: If You Don’t Use related_name
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

