一. 常规做法
利用python类属性和实例属性可以临时添加的特性,在原有相关model中添加统计属性
blog_types = BlogType.objects.all()
blog_types_list = []
for blog_type in blog_types:
# python的类属性可以在需要的时候自定义添加,
# 如blog_type是BlogType的实例,BlogType只有一个blog_name属性,
# 也就是说blog_type有blog_name属性
# 通过blog_type.blog_count给blog_type添加一个新的属性blog_count
blog_type.blog_count = Blog.objects.filter(blog_type=blog_type).count()
blog_types_list.append(blog_type)
context['blog_types'] = blog_types_list
二.利用annotate函数
1. annotate(*args, **kwargs)
通过相关的查询语句,可以QuerySet中的每一个类
查询语句可以是一个简单的值,一个对模型(或任何相关模型)上的字段的引用,或者一个在与QuerySet中对象相关的对象上计算的聚合表达式(平均值、和等)。
annotate()的每个参数都是一个注释,该注释将被添加到返回的QuerySet中的每个对象。
使用关键字参数指定的注释将使用关键字作为注释的别名。
匿名参数将根据聚合函数的名称和聚合的模型字段为它们生成别名。
只有引用单个字段的聚合表达式才能是匿名参数。
其他的都必须是关键字参数。
例如,如果你正在操作一个博客列表,你可能想要确定每个博客中有多少条目:
>>> from django.db.models import Count >>> q = Blog.objects.annotate(Count('entry')) # The name of the first blog >>> q[0].name 'Blogasaurus' # The number of entries on the first blog >>> q[0].entry__count 42
Blog模型本身并不定义entry__count属性,但是通过使用关键字参数指定聚合函数,您可以控制注释的名称:
>>> q = Blog.objects.annotate(number_of_entries=Count('entry')) # The number of entries on the first blog, using the name provided >>> q[0].number_of_entries 42