0

Django にモデル、ビュー、テンプレートがあり、カテゴリの総数を表示したいと考えています。

class Entry (models.Model):
    title = models.CharField(max_length=200)
    category = models.ForeignKey('entry.Category')

class Category(models.Model):
    title = models.CharField(max_length=100)
    parent = models.ForeignKey('self', blank=True, null=True, related_name='children')

def category(request):
    category = Category.objects.all()
    return render_to_response('category.html', locals(), context_instance=RequestContext(request))

<ul>
{% for category in category %}
<li><a href="{{ category.slug }}">{{ category.title }}</a> ({{ category.entry_set.all.count }})</li>
{% endfor %}
</ul>

現在の出力:

-カテゴリー1 (0)

--サブカテゴリー1 (3)

--サブカテゴリー2 (6)

そして、欲望の出力は次のようになります。

-カテゴリー1 (9)

--サブカテゴリー1 (3)

--サブカテゴリー2 (6)

その出力を取得する方法は?

4

2 に答える 2

2

category.entry_set.countの代わりに使用しcategory.entry_set.all.countます。

また、複数の値を参照するために同じ変数名を使用しているcategoryため、変更することをお勧めします。

テンプレートを次のように更新します。

<ul>
{% for cat in category %}
<li><a href="{{ cat.slug }}">{{ cat.title }}</a> ({{ cat.entry_set.count }})</li>
{% endfor %}
</ul>
于 2013-06-16T06:38:21.743 に答える
0

Django-MPTT を使用して解決し、ビューとテンプレートを次のように更新します。

ビュー.py:

def category(request):
    category = Category.tree.add_related_count(Category.objects.all(), Entry, 'category', 'cat_count', cumulative=True)
    return render_to_response('category.html', locals(), context_instance=RequestContext(request))

カテゴリ.html:

{% recursetree category %}
<ul>
<a href="{{ node.slug }}">{{ node.title }} ({{ node.cat_count }})</a>
{% if not node.is_leaf_node %}
<li class="children">
{{ children }}
</li>
{% endif %}
</ul>
{% endrecursetree %}
于 2013-10-26T08:22:45.030 に答える