python-数据库查询操作(聚合函数)-aggregate及annotate用法

book
在这里插入图片描述
book_order
在这里插入图片描述
modles.py

from django.db import models

from django.db import models

class Author(models.Model):
    """作者模型"""
    name = models.CharField(max_length=100)
    age = models.IntegerField()
    email = models.EmailField()

    class Meta:
        db_table = 'author'


class Publisher(models.Model):
    """出版社模型"""
    name = models.CharField(max_length=300)

    class Meta:
        db_table = 'publisher'


class Book(models.Model):
    """图书模型"""
    name = models.CharField(max_length=300)
    pages = models.IntegerField()
    price = models.FloatField()
    rating = models.FloatField()
    author = models.ForeignKey(Author,on_delete=models.CASCADE)
    publisher = models.ForeignKey(Publisher, on_delete=models.CASCADE)

    class Meta:
        db_table = 'book'


class BookOrder(models.Model):
    """图书订单模型"""
    book = models.ForeignKey("Book", on_delete=models.CASCADE)
    price = models.FloatField()
    create_time = models.DateTimeField(auto_now_add=True, null=True)

    class Meta:
        db_table = 'book_order'

views.py

from django.shortcuts import render
from django.http import HttpResponse
from .models import Book, Author,BookOrder
from django.db.models import Avg, Count, Max, Min, Sum
from django.db import connection


def avg_func(request):
    # 获取所有图书的价格平均值 avg
    # filter 过滤条件
    # 聚合函数 aggregate
    # book = Book.objects.aggregate(avg_price=Avg('price'))
    # id大于2价格平均值
    book = Book.objects.filter(id__gt=2).aggregate(avg_price=Avg('price'))
    print(book)
    # print(type(book))
    print(connection.queries)
    return HttpResponse("avg")


def agg_ann_func(request):
    # 每一本图书的销售的平均价格
    # annotate 分组反回值类型->querySet  aggregate 不分组  用于聚合函数
    # books = Book.objects.aggregate(avg=Avg('bookorder__price'))
    books = Book.objects.annotate(avg=Avg('bookorder__price')).filter(avg__gt=90)
    for book in books:
        print(book.name, book.avg)
    print(connection.queries)
    return HttpResponse("agg_ann_func")


def count_func(request):
    # 查询一共有多少本图书
    # books = Book.objects.aggregate(Count("id"))
    # books = Book.objects.aggregate(Count("pk"))
    # books = Book.objects.aggregate(book_nums=Count("pk"))
    # print(books)
    # 查询作者 年龄不重复的有多少个
    # authors = Author.objects.aggregate(count=Count("age", distinct=True))
    # print(authors)
    # 每本图书的销量  __id可以省略不写
    # books = Book.objects.annotate(book_num=Count("bookorder__id"))
    books = Book.objects.annotate(book_num=Count("bookorder"))
    for book in books:
        print(book.name, book.book_num)
    print(connection.queries[-1])
    return HttpResponse("count_func")


def max_min_func(request):
    # author = Author.objects.aggregate(Max("age"), Min("age"))
    # print(author)


    # 每本图书的售卖值的最大和最小
    books = Book.objects.annotate(max=Max("bookorder__price"), min=Min("bookorder__price"))
    for book in books:
        print(book.name, book.max, book.min)
    return HttpResponse("max_min_func")


def sum_func(request):
    # 图书销售的总额
    # book = BookOrder.objects.aggregate(total=Sum("price"))
    # print(book)
    # 每一本图书销售的总额
    # books = Book.objects.annotate(total=Sum("bookorder__price"))
    # for book in books:
    #     print(book.name, book.total)
    #
    # 统计2020年 销售总额
    books = BookOrder.objects.filter(create_time__year=2020).aggregate(total=Sum("price"))
    print(books)
    # 统计每本图书2020年 销售总额
    books = Book.objects.filter(bookorder__create_time__year=2020).annotate(total=Sum("bookorder__price"))
    for book in books:
        print(book.name, book.total)
    return HttpResponse("sum_func")

# F表达式
# 所有人薪水加1000
# 1.提取所有员工的薪资
# 2.在原有的薪资基础上 + 1000
# 3.保存到数据库中


def index(request):
    # users = User.objects.all()
    # for user in users:
    #     user.salary += 1000
    #     user.save()

    user = User.objects.update(salary=F("salary")+1000)
    print(type(user))
    print(connection.queries)

    return HttpResponse("index")

# Q表达式一般用在或运算中
def q_func(request):
    # 价格高于90元,并且评分达到4.8以上评分的
    books = Book.objects.filter(price__gte=90, rating__gte=4.8)
    for book in books:
        print(book.name, book.price, book.rating)
    # 价格高于90元,或者评分达到4.8以上评分的
    books = Book.objects.filter(Q(price__gte=90) | Q(rating__gte=4.8))
    for book in books:
        print(book.name, book.price, book.rating)
    # 获取图书名字中包含“传”,但是id不等于3的图书
    books = Book.objects.filter(Q(name__contains="传") & ~Q(id=3))
    for book in books:
        print(book.name, book.price, book.rating)
    return HttpResponse("q_func")

猜你喜欢

转载自blog.csdn.net/weixin_45905671/article/details/112550137