File tree Expand file tree Collapse file tree 3 files changed +5
-3
lines changed Expand file tree Collapse file tree 3 files changed +5
-3
lines changed Original file line number Diff line number Diff line change 1
1
from django import template
2
+ from django .db .models .aggregates import Count
2
3
3
4
from ..models import Post , Category
4
5
@@ -17,4 +18,5 @@ def archives():
17
18
18
19
@register .simple_tag
19
20
def get_categories ():
20
- return Category .objects .all ()
21
+ # 记得在顶部引入 count 函数
22
+ return Category .objects .annotate (num_posts = Count ('post' )).filter (num_posts__gt = 0 )
Original file line number Diff line number Diff line change @@ -30,7 +30,7 @@ class IndexView(ListView):
30
30
model = Post
31
31
template_name = 'blog/index.html'
32
32
context_object_name = 'post_list'
33
- paginate_by = 1
33
+ paginate_by = 10
34
34
35
35
def get_context_data (self , ** kwargs ):
36
36
"""
Original file line number Diff line number Diff line change @@ -110,7 +110,7 @@ <h3 class="widget-title">分类</h3>
110
110
{% for category in category_list %}
111
111
< li >
112
112
< 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 >
114
114
</ li >
115
115
{% empty %}
116
116
暂无分类!
You can’t perform that action at this time.
0 commit comments