ORM聚合函数详解-准备工作:
如果你用原生SQL
,则可以使用聚合函数来提取数据。比如提取某个商品销售的数量,那么可以使用count,如果想要知道商品销售的平均价格,那么可以使用avg
。聚合函数是通过aggregate
方法来实现的。在讲解这些聚合函数的用法的时候,都是基于以下的模型对象来实现的。
创建如下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() class Meta: db_table = 'book_order'
并创建一个front的app;