Django中Aggregation聚合的基本使用方法
Django 的 filter、exclude 等方法使得對(duì)數(shù)據(jù)庫(kù)的查詢很方便了。這在數(shù)據(jù)量較小的時(shí)候還不錯(cuò),但如果數(shù)據(jù)量很大,或者查詢條件比較復(fù)雜,那么查詢效率就會(huì)很低。
提高數(shù)據(jù)庫(kù)查詢效率可以通過原生 SQL 語(yǔ)句來實(shí)現(xiàn),但是它的缺點(diǎn)就是需要開發(fā)者熟練掌握 SQL。倘若查詢條件是動(dòng)態(tài)變化的,則編寫 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)
接下來可以這樣求所有書籍的平均價(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’)}
如果要獲取所有書籍中的最高價(jià)格:
>>> Book.objects.aggregate(Max(’price’)){’price__max’: Decimal(’44’)}
獲取所有書籍中的最低價(jià)格:
>>> Book.objects.aggregate(Min(’price’)){’price__min’: Decimal(’12’)}
aggregate() 方法返回的不再是 QuerySet 了,而是一個(gè)包含查詢結(jié)果的字典。如果我要對(duì) QerySet 中每個(gè)元素都進(jìn)行聚合計(jì)算、并且返回的仍然是 QuerySet ,那就要用到 annotate() 方法了。
annotate 翻譯過來就是 注解 ,它的作用有點(diǎn)像給 QuerySet 中的每個(gè)元素臨時(shí)貼上一個(gè)臨時(shí)的字段,字段的值是分組聚合運(yùn)算的結(jié)果。
比方說要給查詢集中的每本書籍都增加一個(gè)字段,字段內(nèi)容是外鏈到書籍的作者的數(shù)量:
>>> from django.db.models import Count>>> q = Book.objects.annotate(Count(’authors’))>>> q[0].authors__count3
與 aggregate() 的語(yǔ)法類似,也可以給這個(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)行此類查詢有時(shí)候容易讓人迷惑,如果你對(duì)查詢的結(jié)果有任何的疑問,最好的方法就是直接查看它所執(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í)的相互干擾問題: 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. .NET SkiaSharp 生成二維碼驗(yàn)證碼及指定區(qū)域截取方法實(shí)現(xiàn)2. CentOS郵件服務(wù)器搭建系列—— POP / IMAP 服務(wù)器的構(gòu)建( Dovecot )3. IntelliJ IDEA創(chuàng)建web項(xiàng)目的方法4. css代碼優(yōu)化的12個(gè)技巧5. HTTP協(xié)議常用的請(qǐng)求頭和響應(yīng)頭響應(yīng)詳解說明(學(xué)習(xí))6. Django使用HTTP協(xié)議向服務(wù)器傳參方式小結(jié)7. ASP.NET MVC通過勾選checkbox更改select的內(nèi)容8. 原生JS實(shí)現(xiàn)記憶翻牌游戲9. ASP中實(shí)現(xiàn)字符部位類似.NET里String對(duì)象的PadLeft和PadRight函數(shù)10. 存儲(chǔ)于xml中需要的HTML轉(zhuǎn)義代碼
