一、博客分类统计  之一通过for循环分别统计

1 blog_types = BlogType.objects.all()
2 blog_types_list=[]
3 for blog_type in blog_types:
4     blog_type.blog_count =  Blog.objects.filter(blog_type = blog_type ).count()   #给模型实例化对象blog_type再加一个blog_count属性。
5     blog_types_list.append(blog_type)     

把传出的blog_type_list 赋值给context['blog_types']

1 #  context['blog_types'] = BlogType.objects.all()  变为:
2  context['blog_types'] = blog_types_list

二、修改模板页面  增加({{ blog_type.blog_count }})

1  <ul class="blog-types" >
2                             {% for blog_type in blog_types %}
3                                 <li><a href="{% url 'blogs_with_type' blog_type.pk %}">{{ blog_type.type_name }}({{ blog_type.blog_count }})</a></li>
4                             {% empty %}
5                                 <li>暂无分类</li>
6                             {% endfor %}
7                         </ul>

 三、博客分类统计  之二  使用annotate(注释)拓展字段

from django.db.models import Count  #导入Count方法。

BlogType.objects.annotate(blog_count=Count('blog'))  #由于有外键关联,可以用关联类名的小写,关联外键字段。

context['blog_types'] = BlogType.objects.annotate(blog_count=Count('blog'))

两种方法的区别是:两个原理不同,annotate解析为一个SQL语句,它不被执行,只有被调用时才执行。而for循环是被执行的。

四、对日期归档进行统计

1 blog_dates = Blog.objects.dates('created_time','month',order = "DESC”)
2 blog_dates_dict = {}   #由于构造一个字典存放日期数据
3 for blog_date in blog_dates:
4     blog_count = Blog.objects.filter(created_time__year = blog_date.year,created_time__month = blog_date.month).count()
5     blog_dates_dict[blog_date] = blog_count

网页中修改:

1 <div class="panel-body">
2       <ul class="#">
3              {% for blog_date,blog_count in blog_dates.items %}
4                  <li><a href="{% url 'blogs_with_date' blog_date.year blog_date.month %}">{{ blog_date| date:"Y年m月" }}({{ blog_count }})</a></li>
5                {% endfor %}
6          </ul>

 日期统计也可以用annotate进行统计,但在使用时需要列表和字典转换,更加麻烦一些。

posted on 2018-12-31 23:03  南飞雁ht  阅读(506)  评论(0)    收藏  举报