如何在Django中使用聚合的實(shí)現(xiàn)示例
在本文中,我想向您介紹如何在Django中使用聚合,聚合的含義是“內(nèi)容相關(guān)項(xiàng)的集合,以便它們可以顯示或鏈接到”。在Django中,我們使用的情況例如:
用于在Django模型的數(shù)據(jù)庫(kù)表中查找列的“最大值”,“最小值”。
用于基于列在數(shù)據(jù)庫(kù)表中查找記錄的“計(jì)數(shù)”。
用于查找一組相似對(duì)象的“平均值”值。
還用于查找列中的值的總和。
在大多數(shù)情況下,我們對(duì)數(shù)據(jù)類型為“整數(shù)”,“浮點(diǎn)數(shù)”,“日期”,“日期時(shí)間”等的列使用聚合。
本質(zhì)上,聚合不過(guò)是對(duì)一組行執(zhí)行操作的一種方式。在數(shù)據(jù)庫(kù)中,它們由運(yùn)算符表示為sum,avg等。執(zhí)行這些操作Django在查詢集中添加了兩個(gè)新方法。
這兩種方法是聚合和注釋。我們也可以說(shuō),在sql中,aggregate是一個(gè)沒(méi)有分組依據(jù)的操作(SUM,AVG,MIN,MAX),而annotate是在rowet_table.id上具有分組依據(jù)的操作。 (除非明確覆蓋)。
讓我們從新建一個(gè)工程開(kāi)始:
#創(chuàng)建工程django-admin startproject MyProject#創(chuàng)建應(yīng)用python manage.py startapp Myapp
加應(yīng)用到settings.py文件
INSTALLED_APPS = [ ’django.contrib.admin’, ’django.contrib.auth’, ’django.contrib.contenttypes’, ’django.contrib.sessions’, ’django.contrib.messages’, ’django.contrib.staticfiles’, ’Myapp’ #newly added ]
執(zhí)行migrate命令:
python manage.py migrate
創(chuàng)建管理員用戶:
python manage.py createsuperuser
打開(kāi)Myapp下models.py文件,寫入:
from django.db import models # Create your models here. class Author(models.Model): name = models.CharField(max_length=50) def __str__(self): return self.name class Publisher(models.Model): name = models.CharField(max_length=50) def __str__(self): return self.name class Book(models.Model): name = models.CharField(max_length=300) price = models.DecimalField(max_digits=10, decimal_places=2) authors = models.ManyToManyField(Author) publisher = models.ForeignKey(Publisher, on_delete=models.CASCADE) def __str__(self): return self.name
然后運(yùn)行數(shù)據(jù)庫(kù)遷移命令:
python manage.py makemigrationspython manage.py migrate
注冊(cè)model到admin中,打開(kāi)Myapp下admin.py文件,加入:
from django.contrib import adminfrom .models import Book, Author, Publisher # Register your models here. admin.site.register(Book)admin.site.register(Author)admin.site.register(Publisher)
之后,您需要打開(kāi)管理面板并將一些項(xiàng)目添加到數(shù)據(jù)庫(kù)中。 之后,我們將啟動(dòng)聚合命令。
現(xiàn)在您需要打開(kāi)django shell,因?yàn)槲覀儗jango shell用于我們的聚合命令。
運(yùn)行命令:
python manage.py shell
1、查看總共有多少本書:
In [1]: from MyApp.models import Book In [2]: Book.objects.count()Out[2]: 8
2、查看某出版社下有多少本書?
In [5]: Book.objects.filter(publisher__name = ’Second’)Out[5]: <QuerySet [<Book: Python New Book>, <Book: Kotlin Book>]>
3、查看書的評(píng)價(jià)價(jià)格:
In [6]: from django.db.models import Avg In [7]: Book.objects.all().aggregate(Avg(’price’))Out[7]: {’price__avg’: Decimal(’121.25’)}
4、查看價(jià)格最貴的書價(jià)格:
In [8]: from django.db.models import Max In [9]: Book.objects.all().aggregate(Max(’price’))Out[9]: {’price__max’: Decimal(’185’)}
5、查看價(jià)格最便宜的書價(jià)格:
In [10]: from django.db.models import Min In [11]: Book.objects.all().aggregate(Min(’price’))Out[11]: {’price__min’: Decimal(’50’)}
6、所有書價(jià)格匯總:
In [12]: from django.db.models import Sum In [13]: Book.objects.all().aggregate(Min(’price’))Out[13]: {’price__min’: Decimal(’50’)}
7、混合使用:
In [5]: Book.objects.aggregate(Avg(’price’), Max(’price’), Min(’price’))Out[5]: {’price__avg’: Decimal(’121.25’), ’price__max’: Decimal(’185’), ’price__min’: Decimal(’50’)}
8、annotate使用:
In [9]: from MyApp.models import Publisher In [10]: from django.db.models import Count In [11]: pubs = Publisher.objects.annotate(num_books=Count(’book’)) In [12]: pubs[0].num_booksOut[12]: 3
到此這篇關(guān)于如何在Django中使用聚合的實(shí)現(xiàn)示例的文章就介紹到這了,更多相關(guān)Django使用聚合內(nèi)容請(qǐng)搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
1. 利用promise及參數(shù)解構(gòu)封裝ajax請(qǐng)求的方法2. Nginx+php配置文件及原理解析3. windows服務(wù)器使用IIS時(shí)thinkphp搜索中文無(wú)效問(wèn)題4. .NET中l(wèi)ambda表達(dá)式合并問(wèn)題及解決方法5. JSP數(shù)據(jù)交互實(shí)現(xiàn)過(guò)程解析6. 淺談python出錯(cuò)時(shí)traceback的解讀7. python matplotlib:plt.scatter() 大小和顏色參數(shù)詳解8. Ajax實(shí)現(xiàn)表格中信息不刷新頁(yè)面進(jìn)行更新數(shù)據(jù)9. Python importlib動(dòng)態(tài)導(dǎo)入模塊實(shí)現(xiàn)代碼10. ASP 信息提示函數(shù)并作返回或者轉(zhuǎn)向
