Django模板中的双循环 [英] Double loop in Django template

查看:427
本文介绍了Django模板中的双循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have been trying to do this nested loop for couple of hours, but so far none of my results worked. Here is what i have so far:

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

输出 输出

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

My problem is that SubCategory - News, belongs to Infromation, category Off-Topic belongs to General. For some reason loop displays all of subcategories, and i can't figure out how to narrow it to current Category.

推荐答案

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

You can change the inner loop to:

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

这将循环显示当前类别的子类别.

This will loop over the subcategories for the current category.

由于要在外部循环中遍历类别,因此可以在列表视图中更改查询集以使用Category模型.您可以通过预取子类别来减少查询数量.

Since you are looping over categories in the outer loop, you can change the queryset in the list view to use the Category model. You can cut down the number of queries by prefetching the subcategories.

由于列表视图已经使查询集在模板上下文中可用,因此好像也可以删除get_context_data方法.

It also looks as if you can remove the get_context_data method, since the list view already makes the queryset available in the template context.

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

这篇关于Django模板中的双循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆