zoukankan      html  css  js  c++  java
  • [Django学习] Django基础(7)_分类统计

    一. 常规做法

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

    2. 实例演示

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

    class BlogType(models.Model):
    	type_name = models.CharField(max_length=15)	
    
    	def __str__(self):
    		return self.type_name
    
    
    class 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中

    <a href="{% url 'blogs_with_type' blog_type.pk %}">{{blog_type.type_name}}({{blog_type.blog_count}})</a>
    

      


    注明:学习资料来自“再敲一行代码的个人空间”以及“杨仕航的博客”  

  • 相关阅读:
    一个简单的knockout.js 和easyui的绑定
    knockoutjs + easyui.treegrid 可编辑的自定义绑定插件
    Knockout自定义绑定my97datepicker
    去除小数后多余的0
    Windows Azure Web Site (15) 取消Azure Web Site默认的IIS ARR
    Azure ARM (1) UI初探
    Azure Redis Cache (3) 创建和使用P级别的Redis Cache
    Windows Azure HandBook (7) 基于Azure Web App的企业官网改造
    Windows Azure Storage (23) 计算Azure VHD实际使用容量
    Windows Azure Virtual Network (11) 创建VNet-to-VNet的连接
  • 原文地址:https://www.cnblogs.com/AngryZe/p/9267462.html
Copyright © 2011-2022 走看看