Skip to content

Commit 1438df2

Browse files
author
yangxg
committed
Step21: number of post in category
1 parent 8e34b2a commit 1438df2

File tree

2 files changed

+4
-2
lines changed

2 files changed

+4
-2
lines changed

blog/templatetags/blog_tags.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
from django import template
2+
from django.db.models.aggregates import Count
23

34
from ..models import Post, Category
45

@@ -17,4 +18,5 @@ def archives():
1718

1819
@register.simple_tag
1920
def get_categories():
20-
return Category.objects.all()
21+
# 记得在顶部引入 count 函数
22+
return Category.objects.annotate(num_posts=Count('post')).filter(num_posts__gt=0)

templates/base.html

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -110,7 +110,7 @@ <h3 class="widget-title">分类</h3>
110110
{% for category in category_list %}
111111
<li>
112112
<a href="{% url 'blog:category' category.pk %}">{{ category.name }} <span
113-
class="post-count">(13)</span></a>
113+
class="post-count">({{ category.num_posts }})</span></a>
114114
</li>
115115
{% empty %}
116116
暂无分类!

0 commit comments

Comments
 (0)