Skip to content

Commit b114fb2

Browse files
author
yangxg
committed
Merge branch 'Step21_number-of-post-in-category'
2 parents 2d24d80 + 1438df2 commit b114fb2

File tree

3 files changed

+5
-3
lines changed

3 files changed

+5
-3
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)

blog/views.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@ class IndexView(ListView):
3030
model = Post
3131
template_name = 'blog/index.html'
3232
context_object_name = 'post_list'
33-
paginate_by = 1
33+
paginate_by = 10
3434

3535
def get_context_data(self, **kwargs):
3636
"""

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)