【问题标题】:Double loop in Django templateDjango模板中的双循环
【发布时间】:2017-03-07 23:47:24
【问题描述】:

我已经尝试做这个嵌套循环几个小时了,但到目前为止我的结果都没有奏效。这是我目前所拥有的:

index.html

{% for category in categories %}
    <div class="col-md-12 column category list-group">
        <p><b>{{ category.name }}</b></p>
        {% for subcategory in subcategories %}
            <div class="list-group-item">
                <h5 class="mb-1"><a href="{% url 'subcategory_threads' subcategory.id %}">{{ subcategory.name }}</a></h5>
                <small>{{ subcategory.description }}</small>
                <small>{{ subcategory.count_threads }}</small>
            </div>
        {% endfor %}
    </div>
{% endfor %}

views.py

class IndexView(ListView):
template_name = 'myForum/index.html'
context_object_name = 'SubCategory_list'
queryset = SubCategory.objects.all()


def get_context_data(self, **kwargs):
    context = super(IndexView, self).get_context_data(**kwargs)
    context['categories'] = Category.objects.all()
    context['subcategories'] = SubCategory.objects.all()
    return context

models.py

class Category(models.Model):
name = models.CharField(max_length=255)

def __str__(self):
    return self.name


class SubCategory(models.Model):
name = models.CharField(max_length=255)
description = models.CharField(max_length=255)
category = models.ForeignKey('Category', default=0)

def __str__(self):
    return self.name

输出 Output

我的问题是 SubCategory - News,属于 Infromation,类别 Off-Topic 属于 General。由于某种原因,循环显示所有子类别,我不知道如何将其缩小到当前类别。

【问题讨论】:

    标签: python django loops templates for-loop


    【解决方案1】:

    您可以将内部循环更改为:

    {% for subcategory in category.subcategory_set.all %}
    

    这将遍历当前类别的子类别。

    由于您在外循环中循环分类,您可以更改列表视图中的查询集以使用Category 模型。您可以通过预取子类别来减少查询数量。

    看起来您也可以删除get_context_data 方法,因为列表视图已经使查询集在模板上下文中可用。

    class IndexView(ListView):
        template_name = 'myForum/index.html'
        context_object_name = 'catrgories'
        queryset = Category.objects.all().prefetch_related('subcategory_set') 
    

    【讨论】:

    • 谢谢,我想这可能是我的内循环格式错误。非常感谢。
    猜你喜欢
    • 2017-05-26
    • 1970-01-01
    • 2021-10-17
    • 1970-01-01
    • 2012-07-25
    • 1970-01-01
    • 2012-10-25
    • 2014-02-14
    相关资源
    最近更新 更多