2017-03-07 2 views
0

私はこの入れ子になったループを何時間もやろうとしていましたが、これまでのところ私の結果はどれも働いていませんでした。ここで私はこれまで持っているものです。Djangoテンプレートのダブルループ

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

は私の問題は、そのサブカテゴリです - ニュースは、オフトピックのカテゴリは一般に属し、のinfromationに属します。何らかの理由でループにサブカテゴリがすべて表示され、現在のカテゴリに絞り込む方法がわかりません。

答えて

0

あなたはに内側のループを変更することができます。

{% 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') 
+0

私はそれが私の間違った内部ループのフォーマットかもしれないと思っていました。とても有難い。 –