File tree 4 files changed +8
-4
lines changed
templates/blog/inclusions
4 files changed +8
-4
lines changed Original file line number Diff line number Diff line change @@ -145,6 +145,7 @@ tutorial 分支为项目的主分支,每一篇教程的代码都和历史提
145
145
22 . [ 在脚本中使用 ORM:Faker 批量生成测试数据] ( https://www.zmrenwu.com/courses/hellodjango-blog-tutorial/materials/80/ )
146
146
23 . [ 通过 Django Pagination 实现简单分页] ( https://www.zmrenwu.com/courses/hellodjango-blog-tutorial/materials/81/ )
147
147
24 . [ 稳定易用的 Django 分页库,完善分页功能] ( https://www.zmrenwu.com/courses/hellodjango-blog-tutorial/materials/82/ )
148
+ 25 . [ 统计各个分类和标签下的文章数] ( https://www.zmrenwu.com/courses/hellodjango-blog-tutorial/materials/83/ )
148
149
149
150
## 公众号
150
151
<p align =" center " >
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 , Tag
4
5
@@ -21,13 +22,15 @@ def show_archives(context):
21
22
22
23
@register .inclusion_tag ('blog/inclusions/_categories.html' , takes_context = True )
23
24
def show_categories (context ):
25
+ category_list = Category .objects .annotate (num_posts = Count ('post' )).filter (num_posts__gt = 0 )
24
26
return {
25
- 'category_list' : Category . objects . all () ,
27
+ 'category_list' : category_list ,
26
28
}
27
29
28
30
29
31
@register .inclusion_tag ('blog/inclusions/_tags.html' , takes_context = True )
30
32
def show_tags (context ):
33
+ tag_list = Tag .objects .annotate (num_posts = Count ('post' )).filter (num_posts__gt = 0 )
31
34
return {
32
- 'tag_list' : Tag . objects . all () ,
35
+ 'tag_list' : tag_list ,
33
36
}
Original file line number Diff line number Diff line change @@ -3,7 +3,7 @@ <h3 class="widget-title">分类</h3>
3
3
< ul >
4
4
{% for category in category_list %}
5
5
< li >
6
- < a href ="{% url 'blog:category' category.pk %} "> {{ category.name }} < span class ="post-count "> (13 )</ span > </ a >
6
+ < a href ="{% url 'blog:category' category.pk %} "> {{ category.name }} < span class ="post-count "> ({{ category.num_posts }} )</ span > </ a >
7
7
</ li >
8
8
{% empty %}
9
9
暂无分类!
Original file line number Diff line number Diff line change @@ -3,7 +3,7 @@ <h3 class="widget-title">标签云</h3>
3
3
< ul >
4
4
{% for tag in tag_list %}
5
5
< li >
6
- < a href ="{% url 'blog:tag' tag.pk %} "> {{ tag.name }}</ a >
6
+ < a href ="{% url 'blog:tag' tag.pk %} "> {{ tag.name }} < span class =" post-count " > ({{ tag.num_posts }}) </ a >
7
7
</ li >
8
8
{% empty %}
9
9
暂无标签!
You can’t perform that action at this time.
0 commit comments