示例代码如下:
'''python
#模型要放在app当中。所以首先要在终端命令行窗口,执行命令:
python manage.py startapp front
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'orm_aggregate_demo',
'USER': 'root',
'PASSWORD': 'root',
'HOST': '127.0.0.1',
'PORT': '3306',
}
}
from django.db import models
# 定义作者的模型
class Author(models.Model):
<!-- 指定unique=True,规定字段的唯一性 -->
name = models.CharField(max_length=30, unique=True)
age = models.IntegerField()
email = models.EmailField()
class Meta:
db_table = 'author'
# 定义出版社模型
class Publisher(models.Model):
<!-- 指定unique=True,规定字段的唯一性 -->
name = models.CharField(max_length=100, unique=True)
class Meta:
db_table = 'publisher'
# 定义一个图书模型
class Book(models.Model):
<!-- 指定unique=True,规定字段的唯一性 -->
name = models.CharField(max_length=100, unique=True)
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()
class Meta:
db_table = 'book_order'
终端命令行窗口,执行命令:python manage.py makemigrations(生成相应的迁移脚本)和python manage.py migrate(将生成的迁移脚本映射到数据库中。)
from .models import Book
from django.db.models import Avg
from django.http import HttpResponse
# views.py文件中:
def index(request):
# 聚合函数要放在aggregate()方法中,还有其他的能够执行聚合函数的方法,之后会进行讲解
result = Book.objects.aggregate(Avg('price'))
print(result)
此时打印出的输出结果就是:
{“price__avg”: 价格}
“price__avg”是根据field__avg规则构成的,如果想要修改默认的名字,那么可以将Avg赋值给一个关键字参数。
示例代码如下:
from django.db.models import Avg
result = Book.objects.aggregate(my_avg=Avg('price'))
print(result)
此时打印出的输出结果就是:
{“my_avg”: 价格}
同时我们可以打印出查询的原生SQL语句
from django.db import connection
def inex(request):
result = Book.objects.aggregate(Avg('price'))
print(connection.queries)
# queries中存储了很多的SQL语句。
# 不能够通过print(result.query),进行打印SQL语句。
# 因为result为dict类型,没有query属性。
print(type(result))
result = Book.objects.aggregate(avg=Avg("price"))
from django.db import connection
from .models import Book
from django.http import HttpResponse
from django.db.models import Avg
def index(request):
result = Book.objects.aggregate(Avg('price'))
print(connection.queries)
return HttpResponse("success!")
result = Book.objects.aggregate(book_num=Count('id'))
此时就会返回Book表中图书的数量.
from django.shortcuts import render
from django.http import HttpResponse
from .models import Author,Publisher,Book,BookOrder
from django.db.models import Avg,Count,Sum
from django.db import connection
def index(request):
# 计算同一种书的预定平均价格,使用annotate()方法执行聚合函数,可以进行分组(group by)
# 由父类和子类的模型关系我们知道,子类通过外键的关系了父类,那么django就会在底层为父类添加一个名为子类名字小写形式的方法。
books = Book.objects.annotate(avg=Avg("bookorder__price"))
# print(books)
# 打印出结果:, , , ]>
# 结果显示的是QuerySet类型,可以通过遍历得到具体的图书相关信息
for book in books:
print("%s,%s,平均价格:%s" % (book.name,book.author,book.avg))
# 打印出结果:
# 三国演义,罗贯中,47,[email protected],平均价格:101.5
# 水浒传,施耐庵,57,[email protected],平均价格:107.5
# 红楼梦,曹雪芹,42,[email protected],平均价格:102.0
# 西游记,吴承恩,34,[email protected],平均价格:None
print(connection.queries)
# 打印出结果:[{'sql': 'SELECT @@SQL_AUTO_IS_NULL', 'time': '0.000'}, {'sql': 'SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED', 'time': '0.000'}, {'sql': 'SELECT `book`.`id`, `book`.`name`, `book`.`pages`, `book`.`price`, `book`.`rating`, `book`.`author_id`, `book`.`publisher_id`, AVG(`book_order`.`price`) AS `avg` FROM `book` LEFT OUTER JOIN `book_order` ON (`book`.`id` = `book_order`.`book_id`) GROUP BY `book`.`id` ORDER BY NULL LIMIT 21', 'time': '0.000'}]
return HttpResponse("success !")