如何在另一个用于django的循环中使用

时间:2015-09-01 08:11:03

标签: python django

我正在构建某种列表,其中我们将部分和类别分配给该部分。

在我的view.py中,它看起来像这样:

args['sections'] = ShopSection.objects.all().order_by('name')
args['categories'] =  ShopCategory.objects.all().order_by('-name')

我的模板看起来像这样:

<div class="panel side-panel-1">
<h4 class="title1">Разделы</h4>
<ul class="clear-list">
<li class="">
        <a href="/advert/adverts.aspx">Все разделы</a>
</li>
{% for section in sections %}
    <li class="">
        <!--<a href="/advert/adverts.aspx&sec{{ section.id }}">{{ section.name }}</a>-->
        <a class="" data-dropdown="autoCloseExample" aria-controls="autoCloseExample" aria-expanded="false">
            {{ section.name }} ({{ section.shopcategory_set.count }}) {{section.shopcategory_set.id}} {{ section.id }}
        </a>
        <ul id="autoCloseExample" class="f-dropdown" data-dropdown-content tabindex="-1" aria-hidden="true" aria-autoclose="false" tabindex="-1">

            {% for category in categories %}
            {% if section.id == category.section_id%}
            <li style="width: 100%;"><a href="#">{{ category.name }} sec={{section.id}} cat={{category.id}} catsec={{category.section_id}}</a></li>
            {% else %}
            {% endif %}
            {% endfor %}
        </ul>
{% endfor %}
</ul>

工作页面为here

问题是当我使用{% if section.id == category.section_id %}时,我想根据部分ID过滤类别列表,但section.id未正确定义。

例如:

  • 如果我使用{% if section.id > 3 %},则在周期中将section.id定义为4
  • 如果我使用{% if section.id < 3 %},则在周期中将section.id定义为2

我想要的是

  • -Section id-1
  • - 具有section_id-1
  • 的Category1
  • - 具有section_id-1
  • 的Category2
  • - 具有section_id-1
  • 的Category3
  • -Section id-2
  • - 具有section_id-2
  • 的Category4
  • - Category5具有section_id-2
  • - 具有section_id-2
  • 的Category6

1 个答案:

答案 0 :(得分:1)

如果ShopCategory有一个ForeignKey到ShopSection,那么最干净,最简单的方法是更改​​你的第二个for循环,这样你就不必检查{ {1}}:

section_id
相关问题