标签:mod 1.0 补充 cut app import length res ret
# app01.models.py from django.db import models class Emp(models.Model): name = models.CharField(max_length=32) age = models.IntegerField() salary = models.DecimalField(max_digits=8, decimal_places=2) dep = models.CharField(max_length=32) province = models.CharField(max_length=32) # app01.views.py from django.shortcuts import render, HttpResponse from app01.models import * from django.db.models import Avg, Max, Min, Count def query(request): # -------------------------单表 聚合与分组查询--------------------------- # ------------------------->聚合 aggregate:返回值是一个字典,不再是queryset # 查询所有书籍的平均价格 ret = Book.objects.all().aggregate(avg_price=Avg("price"), max_price=Max("price")) print(ret) # {‘avg_price‘: 151.0, ‘max_price‘: Decimal(‘301.00‘)} ret = Book.objects.aggregate(Avg(‘price‘), Max(‘price‘), Min(‘price‘)) print(ret) # {‘price__avg‘: 151.0, ‘price__max‘: Decimal(‘301.00‘), ‘price__min‘: Decimal(‘12.99‘)} # ------------------------->分组查询 annotate ,返回值依然是queryset # 单表分组查询的ORM语法: 单表模型.objects.values("group by的字段").annotate(聚合函数("统计字段")) # 在单表分组下, 按着主键进行group by是没有任何意义的. # 查询每一个部门的名称以及员工的平均薪水 # select dep,Avg(salary) from emp group by dep ret = Emp.objects.values("dep").annotate(avg_salary=Avg("salary")) print(ret) # <QuerySet [{‘avg_salary‘: 5000.0, ‘dep‘: ‘保安部‘}, {‘avg_salary‘: 51000.0, ‘dep‘: ‘教学部‘}]> # 查询每一个省份的名称以及员工数 ret = Emp.objects.values("province").annotate(c=Count("id")) print(ret) # <QuerySet [{‘province‘: ‘山东省‘, ‘c‘: 2}, {‘province‘: ‘河北省‘, ‘c‘: 1}]> # 补充知识点: # ret=Emp.objects.all() # print(ret) # select * from emp # ret=Emp.objects.values("name") # print(ret) # select name from emp return HttpResponse(‘OK‘)
标签:mod 1.0 补充 cut app import length res ret
原文地址:https://www.cnblogs.com/bubu99/p/10264904.html