Django中Aggregation聚合的基本使用方法
Django 的 filter、exclude 等方法使得對(duì)數(shù)據(jù)庫(kù)的查詢很方便了。這在數(shù)據(jù)量較小的時(shí)候還不錯(cuò),但如果數(shù)據(jù)量很大,或者查詢條件比較復(fù)雜,那么查詢效率就會(huì)很低。
提高數(shù)據(jù)庫(kù)查詢效率可以通過(guò)原生 SQL 語(yǔ)句來(lái)實(shí)現(xiàn),但是它的缺點(diǎn)就是需要開(kāi)發(fā)者熟練掌握 SQL。倘若查詢條件是動(dòng)態(tài)變化的,則編寫(xiě) SQL 會(huì)更加困難。
對(duì)于以便捷著稱的 Django,怎么能忍受這樣的事。于是就有了 Aggregation聚合 。
聚合最好的例子就是官網(wǎng)給的案例了:
# models.pyfrom django.db import modelsclass Author(models.Model): name = models.CharField(max_length=100) age = models.IntegerField()class Publisher(models.Model): name = models.CharField(max_length=300)class Book(models.Model): name = models.CharField(max_length=300) pages = models.IntegerField() price = models.DecimalField(max_digits=10, decimal_places=2) rating = models.FloatField() authors = models.ManyToManyField(Author) publisher = models.ForeignKey(Publisher, on_delete=models.CASCADE) pubdate = models.DateField()class Store(models.Model): name = models.CharField(max_length=300) books = models.ManyToManyField(Book)
接下來(lái)可以這樣求所有書(shū)籍的平均價(jià)格:
>>> from django.db.models import Avg, Max, Min>>> Book.objects.all().aggregate(Avg(’price’)){’price__avg’: Decimal(’30.67’)}
實(shí)際上可以省掉 all() :
>>> Book.objects.aggregate(Avg(’price’)){’price__avg’: Decimal(’30.67’)}
還可以指定返回的鍵名:
>>> Book.objects.aggregate(price_avg=Avg(’price’)){’price_avg’: Decimal(’30.67’)}
如果要獲取所有書(shū)籍中的最高價(jià)格:
>>> Book.objects.aggregate(Max(’price’)){’price__max’: Decimal(’44’)}
獲取所有書(shū)籍中的最低價(jià)格:
>>> Book.objects.aggregate(Min(’price’)){’price__min’: Decimal(’12’)}
aggregate() 方法返回的不再是 QuerySet 了,而是一個(gè)包含查詢結(jié)果的字典。如果我要對(duì) QerySet 中每個(gè)元素都進(jìn)行聚合計(jì)算、并且返回的仍然是 QuerySet ,那就要用到 annotate() 方法了。
annotate 翻譯過(guò)來(lái)就是 注解 ,它的作用有點(diǎn)像給 QuerySet 中的每個(gè)元素臨時(shí)貼上一個(gè)臨時(shí)的字段,字段的值是分組聚合運(yùn)算的結(jié)果。
比方說(shuō)要給查詢集中的每本書(shū)籍都增加一個(gè)字段,字段內(nèi)容是外鏈到書(shū)籍的作者的數(shù)量:
>>> from django.db.models import Count>>> q = Book.objects.annotate(Count(’authors’))>>> q[0].authors__count3
與 aggregate() 的語(yǔ)法類(lèi)似,也可以給這個(gè)字段自定義個(gè)名字:
>>> q = Book.objects.annotate(a_count=Count(’authors’))
跨外鏈查詢字段也是可以的:
>>> s = Store.objects.annotate(min_price=Min(’books__price’), max_price=Max(’books__price’))>>> s[0].min_priceDecimal(’12’)>>> s[0].max_priceDecimal(’44’)
既然 annotate() 返回的是查詢集,那么自然也可以和 filter() 、 exclude() 等查詢方法組合使用:
>>> b = Book.objects.filter(name__startswith='Django').annotate(num_authors=Count(’authors’))>>> b[0].num_authors4
聯(lián)用的時(shí)候 filter 、 annotate 的順序會(huì)影響返回結(jié)果,所以邏輯要想清楚。
也可以排序:
>>> Book.objects.annotate(num_authors=Count(’authors’)).order_by(’num_authors’)
總而言之, aggregate 和 annotate 用于組合查詢。當(dāng)你需要對(duì)某些字段進(jìn)行聚合操作時(shí)(比如Sum, Avg, Max),請(qǐng)使用 aggregate 。如果你想要對(duì)數(shù)據(jù)集先進(jìn)行分組(Group By)然后再進(jìn)行某些聚合操作或排序時(shí),請(qǐng)使用 annotate 。
進(jìn)行此類(lèi)查詢有時(shí)候容易讓人迷惑,如果你對(duì)查詢的結(jié)果有任何的疑問(wèn),最好的方法就是直接查看它所執(zhí)行的 SQL 原始語(yǔ)句,像這樣:
>>> b = Book.objects.annotate(num_authors=Count(’authors’)).order_by(’num_authors’)>>> print(b.query)SELECT 'aggregation_book'.'id', 'aggregation_book'.'name','aggregation_book'.'pages', 'aggregation_book'.'price','aggregation_book'.'rating', 'aggregation_book'.'publisher_id', 'aggregation_book'.'pubdate', COUNT('aggregation_book_authors'.'author_id') AS 'num_authors' FROM 'aggregation_book' LEFT OUTER JOIN 'aggregation_book_authors' ON ('aggregation_book'.'id' = 'aggregation_book_authors'.'book_id') GROUP BY 'aggregation_book'.'id', 'aggregation_book'.'name','aggregation_book'.'pages', 'aggregation_book'.'price','aggregation_book'.'rating', 'aggregation_book'.'publisher_id', 'aggregation_book'.'pubdate'ORDER BY 'num_authors' ASC
相關(guān)文檔: Aggregation
復(fù)合使用聚合時(shí)的相互干擾問(wèn)題: Count and Sum annotations interfere with each other
總結(jié)
到此這篇關(guān)于Django中Aggregation聚合的基本使用方法就介紹到這了,更多相關(guān)Django Aggregation聚合使用內(nèi)容請(qǐng)搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
1. 前端從瀏覽器的渲染到性能優(yōu)化2. 無(wú)線標(biāo)記語(yǔ)言(WML)基礎(chǔ)之WMLScript 基礎(chǔ)第1/2頁(yè)3. ASP刪除img標(biāo)簽的style屬性只保留src的正則函數(shù)4. 讀大數(shù)據(jù)量的XML文件的讀取問(wèn)題5. 解析原生JS getComputedStyle6. PHP循環(huán)與分支知識(shí)點(diǎn)梳理7. css代碼優(yōu)化的12個(gè)技巧8. 利用CSS3新特性創(chuàng)建透明邊框三角9. ASP實(shí)現(xiàn)加法驗(yàn)證碼10. ASP基礎(chǔ)入門(mén)第三篇(ASP腳本基礎(chǔ))
