Django 聚合函數(shù)的具體使用
orm模型中的聚合函數(shù)跟MySQL中的聚合函數(shù)作用是一致的,也有像Sum、Avg、Count、Max、Min,接下來我們逐個介紹
聚合函數(shù)所有的聚合函數(shù)都是放在django.db.models下面。并且聚合函數(shù)不能夠單獨的執(zhí)行,聚合函數(shù)是通過aggregate方法來實現(xiàn)的。在說明聚合函數(shù)的用法的時候,都是基于以下的模型對象來實現(xiàn)的。
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’Avg
Avg:求平均值。比如想要獲取所有圖書的價格平均值。那么可以使用以下代碼實現(xiàn)。
from django.db.models import Avg result = Book.objects.aggregate(Avg(’price’)) print(result)
以上的打印結(jié)果是:
{'price__avg':23.0}
其中price__avg的結(jié)構(gòu)是根據(jù)field__avg規(guī)則構(gòu)成的。如果想要修改默認的名字,那么可以將Avg賦值給一個關(guān)鍵字參數(shù)。示例代碼如下:
from django.db.models import Avg result = Book.objects.aggregate(my_avg=Avg(’price’)) print(result)
以上的打印結(jié)果為
{'my_avg':23}
CountCount:獲取指定的對象的個數(shù)。示例代碼如下:
from django.db.models import Count result = Book.objects.aggregate(book_num=Count(’id’))
以上的result將返回Book表中總共有多少本圖書。
Count類中,還有另外一個參數(shù)叫做distinct,默認是等于False,如果是等于True,那么將去掉那些重復(fù)的值。比如要獲取作者表中所有的不重復(fù)的郵箱總共有多少個,那么可以通過以下代碼來實現(xiàn):
from djang.db.models import Countresult = Author.objects.aggregate(count=Count(’email’,distinct=True))Max和Min
Max和Min:獲取指定對象的最大值和最小值。比如想要獲取Author表中,最大的年齡和最小的年齡分別是多少。那么可以通過以下代碼來實現(xiàn):
from django.db.models import Max,Minresult = Author.objects.aggregate(Max(’age’),Min(’age’))
如果最大的年齡是90,最小的年齡是10。那么以上的result將為:
{'age__max':90,'age__min':10}
SumSum:求指定對象的總和。比如要求圖書的銷售總額。那么可以使用以下代碼實現(xiàn):
from djang.db.models import Sumresult = Book.objects.annotate(total=Sum('bookorder__price'))
以上的代碼annotate的意思是給Book表在查詢的時候添加一個字段叫做total,這個字段的數(shù)據(jù)來源是從BookOrder模型的price的總和而來。
aggregate和annotate的區(qū)別相同點:這兩個方法都可以執(zhí)行聚合函數(shù)。
不同點:
aggregate返回的是一個字典,在這個字典中存儲的是這個聚合函數(shù)執(zhí)行的結(jié)果。而annotate返回的是一個QuerySet對象,并且會在查找的模型上添加一個聚合函數(shù)的屬性。 aggregate不會做分組,而annotate會使用group by子句進行分組,只有調(diào)用了group by子句,才能對每一條數(shù)據(jù)求聚合函數(shù)的值。F表達式:F表達式: 動態(tài)的獲取某個字段上的值。并且這個F表達式,不會真正的去數(shù)據(jù)庫中查詢數(shù)據(jù),他相當(dāng)于只是起一個標識的作用。比如想要將原來每本圖書的價格都在原來的基礎(chǔ)之上增加10元,那么可以使用以下代碼來實現(xiàn):
from django.db.models import FBook.objects.update(price=F('price')+10) Q表達式
Q表達式:使用Q表達式包裹查詢條件,可以在條件之間進行多種操作。與/或非等,從而實現(xiàn)一些復(fù)雜的查詢操作。例子如下:
查找價格大于100,并且評分達到4.85以上的圖書:
# 不使用Q表達式的 books = Book.objects.filter(price__gte=100,rating__gte=4.85) # 使用Q表達式的 books = Book.objects.filter(Q(price__gte=100)&Q(rating__gte=4.85))
查找價格低于100元,或者評分低于4分的圖書:
books = Book.objects.filter(Q(price__gte=100)&Q(rating__gte=4.85))
獲取價格大于100,并且圖書名字中不包含”傳“字的圖書:
books = Book.objects.filter(Q(price__gte=100)&~Q(name__icontains=’傳’))
到此這篇關(guān)于Django 聚合函數(shù)的具體使用的文章就介紹到這了,更多相關(guān)Django 聚合函數(shù)內(nèi)容請搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
1. idea設(shè)置提示不區(qū)分大小寫的方法2. Java利用TCP協(xié)議實現(xiàn)客戶端與服務(wù)器通信(附通信源碼)3. 使用AJAX(包含正則表達式)驗證用戶登錄的步驟4. 利用ajax+php實現(xiàn)商品價格計算5. IDEA 2020.1.2 安裝教程附破解教程詳解6. JS圖片懶加載庫VueLazyLoad詳解7. Java PreparedStatement用法詳解8. django queryset相加和篩選教程9. Spring如何集成ibatis項目并實現(xiàn)dao層基類封裝10. IntelliJ IDEA導(dǎo)出項目的方法

網(wǎng)公網(wǎng)安備