Skip to content

Commit bef24bd

Browse files
author
zmrenwu
committedJan 1, 2020
Step25: number of posts in category and tag
1 parent 4113bfc commit bef24bd

File tree

4 files changed

+8
-4
lines changed

4 files changed

+8
-4
lines changed
 

‎README.md

+1
Original file line numberDiff line numberDiff line change
@@ -145,6 +145,7 @@ tutorial 分支为项目的主分支,每一篇教程的代码都和历史提
145145
22. [在脚本中使用 ORM:Faker 批量生成测试数据](https://www.zmrenwu.com/courses/hellodjango-blog-tutorial/materials/80/)
146146
23. [通过 Django Pagination 实现简单分页](https://www.zmrenwu.com/courses/hellodjango-blog-tutorial/materials/81/)
147147
24. [稳定易用的 Django 分页库,完善分页功能](https://www.zmrenwu.com/courses/hellodjango-blog-tutorial/materials/82/)
148+
25. [统计各个分类和标签下的文章数](https://www.zmrenwu.com/courses/hellodjango-blog-tutorial/materials/83/)
148149

149150
## 公众号
150151
<p align="center">

‎blog/templatetags/blog_extras.py

+5-2
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, Tag
45

@@ -21,13 +22,15 @@ def show_archives(context):
2122

2223
@register.inclusion_tag('blog/inclusions/_categories.html', takes_context=True)
2324
def show_categories(context):
25+
category_list = Category.objects.annotate(num_posts=Count('post')).filter(num_posts__gt=0)
2426
return {
25-
'category_list': Category.objects.all(),
27+
'category_list': category_list,
2628
}
2729

2830

2931
@register.inclusion_tag('blog/inclusions/_tags.html', takes_context=True)
3032
def show_tags(context):
33+
tag_list = Tag.objects.annotate(num_posts=Count('post')).filter(num_posts__gt=0)
3134
return {
32-
'tag_list': Tag.objects.all(),
35+
'tag_list': tag_list,
3336
}

‎templates/blog/inclusions/_categories.html

+1-1
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ <h3 class="widget-title">分类</h3>
33
<ul>
44
{% for category in category_list %}
55
<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>
77
</li>
88
{% empty %}
99
暂无分类!

‎templates/blog/inclusions/_tags.html

+1-1
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ <h3 class="widget-title">标签云</h3>
33
<ul>
44
{% for tag in tag_list %}
55
<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>
77
</li>
88
{% empty %}
99
暂无标签!

0 commit comments

Comments
 (0)
Please sign in to comment.