这是我的模型
class MainCategory(models.Model):
name = models.CharField(max_length=100)
def __str__(self) :
return self.name
class Category(models.Model):
main_category = models.ForeignKey(MainCategory, on_delete=models.CASCADE, related_name="maincategory")
name = models.CharField(max_length=100)
def __str__(self) :
return self.name + "--" + self.main_category.name
class SubCategory(models.Model):
category = models.ForeignKey(Category, on_delete=models.CASCADE, related_name="category_name")
name = models.CharField(max_length=100)
def __str__(self) :
return self.name
检视方式
def Home(request):
sliders = Slider.objects.all()
banners = BannerArea.objects.all()
main_category = MainCategory.objects.all()
context = {
'sliders' : sliders,
'banners' : banners,
'main_category' : main_category
}
return render(request, 'main/home.html', context)
我想显示主类别和子类别和类别。显示主类别,但不显示子类别和类别。你能帮我解决这个问题吗
Header.html文件
<div class="cat__menu">
<nav id="mobile-menu" style="display: block;">
<ul>
{% for i in main_category %}
<li>
<a href="shop.html"> {{ i.name }} <i class="far fa-angle-down"></i></a>
<ul class="mega-menu">
{% for cat in i.category_set.all %}
<li><a href="shop.html">{{cat.name}}</a>
<ul class="mega-item">
{% for sub_cat in cat.subcategory_set.all %}
<li><a href="product-details.html">{{sub_cat.name}}</a></li>
{% endfor %}
</ul>
</li>
{% endfor %}
</ul>
</li>
{% endfor %}
</ul>
</nav>
</div>
我想显示主类别和子类别和类别。显示主类别,但不显示子类别和类别。你能帮我解决这个问题吗
1条答案
按热度按时间fxnxkyjh1#
它不起作用,因为您已经为反向关系定义了相关名称。因此,您应该使用相关名称而不是
<modelname>_set
,如下所示: