Mat Kolodziej
Mat Kolodziej

Reputation: 3

Double loop in Django template

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

Output Output

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.

Upvotes: 0

Views: 2937

Answers (1)

Alasdair
Alasdair

Reputation: 309109

You can change the inner loop to:

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

This will loop over the subcategories for the current 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.

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') 

Upvotes: 1

Related Questions