Python Django子类别

时间:2018-01-16 11:32:32

标签: python django django-templates

我想打印每个主类别的子类别名称。以下代码现在显示每个Main类别的所有子类别。我该怎么办?

的index.html

{% for mainCatList in main_cat_list %}
    <li class="subMenu"><a>{{ mainCatList.main_category_name }}</a>
        <ul>
        {% for subCat in cat_list %}
            <li><a href="products.html"><i class="icon-chevron-right"></i>{{ subCat.category_name }}</a></li>
        {% endfor %}
        </ul>
    </li>
{% endfor %}

views.html

from django.shortcuts import render                          
from .models import Product, Category, Main_Category


def homePageView(request):

    main_cat_list = Main_Category.objects.all()
    cat_list = Category.objects.all()

    context = {'main_cat_list': main_cat_list, 'cat_list': cat_list}
    return render(request, 'index.html', context)

1 个答案:

答案 0 :(得分:1)

我假设您的类别具有Main_Catagory的外键。在这种情况下,你可以这样做

{% for main_cat in main_cat_list %}
<li class="subMenu"><a>{{ main_cat.main_category_name }}</a>
    <ul>
        {% for sub_cat in main_cat.category_set.all %}
        <li><a href="products.html"><i class="icon-chevron-right"></i>{{ sub_cat.category_name }}</a></li>
        {% endfor %}
    </ul>
</li>
{% endfor %}