Lius 2020-05-11
使用方法: 类名.objects.aggregate(聚合函数名(‘表的列名‘)) 聚合函数名: Avg 平均值 Count数量 Max 最大 Min 最小 Sum 求和 示例: Student.objects.aggregate(Max(‘sage‘))
创建消费者数据表 Customer class Customer(models.Model): c_name = models.CharField(max_length = 16) # 消费者名字 c_cost = models.IntegerField(default = 10) # 消费的金额
产生迁移文件 python manage.py makemigrations 进行迁移 python manage.py migrate
设置数据
Max 示例
def getcostmax(request): cost_max = Customer.objects.aggregate(Max("c_cost")) print(cost_max) return HttpResponse("获取成功")
Min 示例
def getcostmin(request): cost_min = Customer.objects.aggregate(Min("c_cost")) print(cost_min) return HttpResponse("获取成功") 注: 不要忘记在 urls.py 中进行注册
Sum 示例
def getcostsum(request): cost_sum = Customer.objects.aggregate(Sum("c_cost")) print(cost_sum) return HttpResponse("获取成功")
Count 示例
def getcustomercount(request): customer_count = Customer.objects.aggregate(Count("c_name")) print(customer_count) return HttpResponse("获取成功") 注: 此时获取姓名即可,不用获取价格
Avg 示例
def getcostavg(request): cost_avg = Customer.objects.aggregate(Avg("c_cost")) print(cost_avg) return HttpResponse("获取成功")
导入的包 from django.db.models import Max, Min, Sum, Count, Avg from django.http import HttpResponse from django.shortcuts import render # Create your views here. from app5.models import User, Order, Grade, Customer
2020-05-11