表模型
from django.db import models
# Create your models here.
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)
pub_time = models.DateTimeField(auto_now_add=True, null=True)
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'
aggregate
- aggregate的中文意思是聚合, 与SQL底层的聚合函数是一样的。
- Django的aggregate()方法作用的结果是以字典(Dict)格式返回。
举例说明
使用聚合函数之前先导入所使用的聚合函数
from django.db.models import Avg, Max, Min
- 计算book表里price字段的平均值
book = Book.objects.aggregate(avg=Avg("price"))
- 查找评分最高的书籍
book = Book.objects.aggregate(max=Max('rating'))
- 查找评分最低的书籍
book = Book.objects.aggregate(min=Min('rating'))
annotate
- annotate的中文意思是注释,一个更好的理解是分组(Group By)。
- 与aggregate方法不同的是,annotate方法返回结果的不仅仅是含有统计结果的一个字典,而是包含有新增统计字段的查询集(queryset)。
举例说明
使用聚合函数之前先导入所使用的聚合函数
from django.db.models import Count
- 以书籍为分组,查找每个书籍订单的数量
books = Book.objects.annotate(count=Count('bookorder__price'))
- 以出版社为分组,查找每组书籍的数量
publisher = Publisher.objects.annotate(count=Count('book__id'))