[Django学习] Django基础(7)_分类统计
发布日期:2021-08-31 13:57:41 浏览次数:34 分类:技术文章

本文共 2589 字,大约阅读时间需要 8 分钟。

一. 常规做法

  利用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__count42

  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_entries42

2. 实例演示

  (1)两个模型,用外键关联

class BlogType(models.Model):	type_name = models.CharField(max_length=15)		def __str__(self):		return self.type_nameclass Blog(models.Model):	title = models.CharField(max_length=50)	blog_type = models.ForeignKey(BlogType, on_delete=models.DO_NOTHING)    #second method: blog_type = models.ForeignKey(BlogType, on_delete=models.DO_NOTHING, related_name="blog_blogType")	content = models.TextField()	author = models.ForeignKey(User, on_delete=models.DO_NOTHING)	create_time = models.DateTimeField(auto_now_add=True)	last_update = models.DateTimeField(auto_now=True)

  

  (2)views.py中,调用annotate

    blog_count 为关键字参数,

    Count()为聚合函数,

    'blog'是与BlogType模型关联的Blog模型的小写

或者  在Blog模型中的blog_type定义时,指定其related_name="blog_blogType",在Count函数中引用"blog_blogType"

  context={}  context['blogs'] = page_of_blogs.object_list  context['page_of_blogs'] = page_of_blogs  context['page_range'] = page_range  context['blog_types'] = BlogType.objects.annotate(blog_count=Count('blog'))#second method: context['blog_types'] = BlogType.objects.annotate(blog_count=Count('blog_blogType'))  context['blog_dates'] = Blog.objects.dates('create_time','month',order='DESC')

  (3)templates中

  


注明:学习资料来自以及  

转载于:https://www.cnblogs.com/AngryZe/p/9267462.html

转载地址:https://blog.csdn.net/weixin_34077371/article/details/93137449 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:EF中新建表和关联表的方法
下一篇:适合程序员学习的网站

发表评论

最新留言

逛到本站,mark一下
[***.202.152.39]2024年04月05日 01时07分58秒