最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Django 聚合查詢及使用步驟

 更新時間:2024年09月23日 10:53:28   作者:拾伍廿肆  
本文詳細介紹了Django中聚合查詢的使用方法和步驟,包括aggregate()和annotate()兩種聚合查詢方式,以及F()和Q()查詢的使用場景,文中通過具體代碼示例解釋了如何在Django項目中實現(xiàn)數(shù)據(jù)聚合,感興趣的朋友跟隨小編一起看看吧

一、聚合查詢

使用聚合查詢前要先從 django.db.models 引入 Avg、Max、Min、Count、Sum(首字母大寫)
聚合查詢返回值的數(shù)據(jù)類型是字典

聚合查詢使用aggregate()對查詢集執(zhí)行聚合操作,它允許我們使用數(shù)據(jù)庫提供的聚合函數(shù)(如 COUNT(), AVG(), SUM(), MAX(), MIN() 等)來對查詢集中的數(shù)據(jù)進行匯總計算,aggregate() 方法返回一個字典,字典的鍵是你指定的聚合函數(shù)別名,值是聚合計算的結(jié)果

queryset.aggregate(聚合函數(shù))
# 別名使用
queryset.aggregate(別名 = 聚合函數(shù)名("屬性名稱"))
# 例:
result = Book.objects.aggregate(average_price=Avg('price'), total_books=Count('id'))
# 結(jié)果示例: {'average_price': 100.25, 'total_books': 150}

二、使用步驟

1.準備工作

還是之前那個fa的項目目錄,在views.py內(nèi)引入

# 導(dǎo)入聚合函數(shù)
from django.db.models import Avg,Max,Min,Count,Sum

在models.py里面,定義一個Book模型

class Book(models.Model):
    title = models.CharField(max_length=255)  # 書名
    author = models.CharField(max_length=255)  # 作者
    price = models.DecimalField(max_digits=10, decimal_places=2)  # 價格
    rating = models.FloatField()  # 評分
    published_date = models.DateField()  # 出版日期
    pages = models.IntegerField()  # 頁數(shù)
    def __str__(self):
        return self.title

在數(shù)據(jù)庫生成book表,執(zhí)行下列命令

python manage.py makemigrations
python manage.py migrate

這個時候我們就有一張book的表了,我們自己手動塞入一些數(shù)據(jù)(這里就不做新增了),然后在下一步實現(xiàn)聚合函數(shù)的使用
隨意添加的數(shù)據(jù)

2.具體使用

定義一個方法去使用聚合函數(shù),我們在views.py里面添加一個方法

def getBookSomeInfo(request):
    # 計算書的平均價格
    average_price = models.Book.objects.aggregate(avg_price = Avg('price'))
    # 如果不加別名結(jié)果為: {'price__avg': 100.25}
    # 獲取書的最高價格
    max_price = models.Book.objects.aggregate(Max('price'))
    # 獲取書的最低價格
    min_price = models.Book.objects.aggregate(min_price = Min('price'))
    # 統(tǒng)計書的總數(shù)量
    # book_count = models.Book.objects.aggregate(Count('id'))
    book_count = models.Book.objects.aggregate(book_count = Count('id'))
    # 其實也可以使用 len(models.Book.objects.all()) / models.Book.objects.count()
    # 計算所有書的總價格
    total_price = models.Book.objects.aggregate(total_price = Sum('price'))
    return HttpResponse(f"平均價格: {average_price}, 最高價格: {max_price}, 最低價格: {min_price}, 總數(shù)量: {book_count}, 總價格: {total_price}")

在路由urls.py里面添加

    path('getBookSomeInfo', views.getBookSomeInfo, name='getBookSomeInfo'),

訪問鏈接http://127.0.0.1:8082/article/getBookSomeInfo

3.分組查詢(annotate)

1.定義

annotate() 是 Django ORM 提供的一個方法,用于在查詢集中為每個對象添加計算值。與 aggregate() 方法不同,annotate() 是逐個對象進行計算,而 aggregate() 是對整個查詢集進行計算,并返回一個匯總結(jié)果

2.使用

使用前要先從 django.db.models 引入聚合函數(shù),annotate() 方法接受一個或多個聚合函數(shù)作為參數(shù),這些聚合函數(shù)會被應(yīng)用到查詢集中,并將結(jié)果作為額外字段添加到每個對象上

queryset.annotate(聚合函數(shù))

3.具體案例

我們先修改一下剛剛定義的Book模型,同時增加一個作者User模型

class User(models.Model):
    name = models.CharField(max_length=255)  # 作者名稱
    def __str__(self):
        return self.name
class Book(models.Model):
    title = models.CharField(max_length=255)  # 書名
    # author = models.CharField(max_length=255)  # 作者
    user = models.ForeignKey(User, related_name='books', null=True, on_delete=models.CASCADE)  # 作者
    price = models.DecimalField(max_digits=10, decimal_places=2)  # 價格
    rating = models.FloatField()  # 評分
    published_date = models.DateField()  # 出版日期
    pages = models.IntegerField()  # 頁數(shù)
    def __str__(self):
        return self.title

執(zhí)行命令生成數(shù)據(jù)表,user表和book表都先手動寫入數(shù)據(jù),不通過程序?qū)懭霐?shù)據(jù)
views.py增加方法

def getBookFormUser(request):
    # 計算每個作者的書籍?dāng)?shù)量
    # 這里的 'books' 是 models.User 類中定義的外鍵名稱,如果外鍵名稱不是 'books' 則需要修改
    users_with_book_count = models.User.objects.annotate(book_count = Count('books'))
    users_with_book_count_str = ''
    # 輸出每個作者的書籍?dāng)?shù)量
    for user in users_with_book_count:
        users_with_book_count_str += f"{user.name} has {user.book_count} books.\n"
    # 計算每個作者的書籍平均價格
    # books__price 代表 books 外鍵的 price 字段
    users_with_avg_price = models.User.objects.annotate(avg_price = Avg('books__price'))
    users_with_avg_price_str = ''
    # 輸出每個作者的書籍平均價格
    for user in users_with_avg_price:
        users_with_avg_price_str += f"{user.name} has an average book price of {user.avg_price}.\n"
    # 計算每個作者的書籍總價格和最高評分
    users_with_totals = models.User.objects.annotate(total_price = Sum('books__price'), highest_rating = Max('books__rating'))
    users_with_totals_str = ''
    # 輸出每個作者的書籍總價格和最高評分
    for user in users_with_totals:
        users_with_totals_str += f"{user.name} has a total book price of {user.total_price} and the highest rating is {user.highest_rating}.\n"
    # 返回帶有換行符的 HTML 響應(yīng),確保編碼為UTF-8
    return HttpResponse(
        f"每個作者的書籍?dāng)?shù)量: <br>{users_with_book_count_str}<br>"
        f"每個作者的書籍平均價格: <br>{users_with_avg_price_str}<br>"
        f"每個作者的書籍總價格和最高評分: <br>{users_with_totals_str}",
        content_type="text/html; charset=utf-8"
    )

增加路由

path('getBookFormUser', views.getBookFormUser, name='getBookFormUser'),

訪問鏈接http://127.0.0.1:8000/article/getBookFormUser

4.F() 查詢

1.定義

F() 表達式用于在數(shù)據(jù)庫中直接引用字段的值,而不是將值從數(shù)據(jù)庫取出后再進行計算。它允許你在數(shù)據(jù)庫層面進行原子性的計算操作,從而避免出現(xiàn)競爭條件或數(shù)據(jù)不同步的問題,常用于以下場景:

對字段值進行加減、乘除等數(shù)學(xué)運算。
比較同一個模型中不同字段的值。
更新字段時直接使用該字段的當(dāng)前值。

2.使用

要使用 F() 表達式,你需要從 django.db.models 中導(dǎo)入 F 類

from django.db.models import F

字段值的更新(如:增加瀏覽數(shù))

先更新一下Book模型

class Book(models.Model):
    title = models.CharField(max_length=255)  # 書名
    # author = models.CharField(max_length=255)  # 作者
    user = models.ForeignKey(User, related_name='books', null=True, on_delete=models.CASCADE)  # 作者
    price = models.DecimalField(max_digits=10, decimal_places=2)  # 價格
    rating = models.FloatField()  # 評分
    published_date = models.DateField()  # 出版日期
    pages = models.IntegerField()  # 頁數(shù)
    views = models.IntegerField(default=0)  # 瀏覽量
    def __str__(self):
        return self.title

定義方法和路由

def addViews(request):
    # 增加閱讀量
    article_id = 1
    models.Book.objects.filter(id=article_id).update(views=F('views') + 1)
    return HttpResponse('Views added successfully')
path('addViews', views.addViews, name='addViews'),

訪問鏈接http://127.0.0.1:8000/article/addViews

一些其他場景
定義方法和路由

def someOtherInfo(request):
    # 比較同一個模型的兩個字段的值
    # 獲取 price 大于 discount_price 的商品,這個查詢會返回所有 price 大于 discount_price 的 Product 實例
    # 注意:F() 函數(shù)用于引用其他字段的值,不能用于直接比較兩個字段的值,price和views都是字段名
    book_gt_discount = models.Book.objects.filter(price__gt=F('views'))
    book_gt_discount_str = ''
    for item in book_gt_discount:
        book_gt_discount_str += f"Book {item.id} has a price of {item.price} and views of {item.views}\n"
    # 多字段運算
    # 獲取所有books的總價格和評分的乘積
    # 使用 F() 表達式在 annotate 中
    books = models.Book.objects.annotate(total_price=F('price') * F('views'))
    str_books = ''
    for item in books:
        str_books += f"Book {item.id} has total price {item.total_price}\n"
    # 查詢時對字段進行運算
    # 獲取book的價格大于其views加500的書籍
    high_books = models.Book.objects.filter(price__gt=F('views') + 500.00)
    high_books_str = ''
    for item in high_books:
        high_books_str += f"Book {item.id} has a price of {item.price}\n"
    return HttpResponse(
        f"book_gt_discount: <br>{book_gt_discount_str}<br>"
        f"str_books: <br>{str_books}<br>"
        f"high_books_str: <br>{high_books_str}",
        content_type="text/html; charset=utf-8"
    )
path('someOtherInfo', views.someOtherInfo, name='someOtherInfo'),

訪問鏈接http://127.0.0.1:8000/article/someOtherInfo

5.Q() 查詢

1.定義

Q() 對象來自 django.db.models,用于創(chuàng)建復(fù)雜的查詢條件。你可以使用它來結(jié)合多個條件,執(zhí)行與(AND)或或(OR)操作,甚至是非(NOT)操作,尤其是在需要執(zhí)行“OR”操作或者需要多個條件組合時非常有用。Q() 對象使得構(gòu)建復(fù)雜的查詢變得更加靈活和強大,
使用前還是先導(dǎo)入

from django.db.models import Q

2.查詢

定義方法和路由

def searchByq(request):
    # 按價格和閱讀量查詢書籍
    # 注意:Q() 函數(shù)用于構(gòu)建復(fù)雜的查詢條件,可以與其他條件組合使用
    # 這里的 Q() 函數(shù)與 price__gt 條件組合使用,表示價格大于 500.00
    # 與 views__gt 條件組合使用,表示閱讀量大于 1
    books_and = models.Book.objects.filter(Q(price__gt=500.00) & Q(views__gt=1))
    books_and_str = ''
    for item in books_and:
        books_and_str += f"Book {item.id} has a price of {item.price} and views of {item.views}\n"
    # 按價格或閱讀量查詢書籍
    # 這里的 Q() 函數(shù)與 price__gt 條件組合使用,表示價格大于 500.00
    # 與 views__gt 條件組合使用,表示閱讀量大于 1
    books_or = models.Book.objects.filter(Q(price__gt=500.00) | Q(views__gt=1))
    books_or_str = ''
    for item in books_or:
        books_or_str += f"Book {item.id} has a price of {item.price} and views of {item.views}\n"
    # 按價格范圍查詢書籍
    # 這里的 Q() 函數(shù)與 price__range 條件組合使用,表示價格在 500.00 到 1000.00 之間
    books_range = models.Book.objects.filter(Q(price__range=(500.00, 1000.00)))
    books_range_str = ''
    for item in books_range:
        books_range_str += f"Book {item.id} has a price of {item.price}\n"
    # not 查詢 這里使用的 ~Q() 函數(shù)表示價格不大于 500.00
    books_not = models.Book.objects.filter(~Q(price__gt=500.00))
    books_not_str = ''
    for item in books_not:
        books_not_str += f"Book {item.id} has a price of {item.price}\n"
    return HttpResponse(
        f"books_and_str: <br>{books_and_str}<br>"
        f"books_or_str: <br>{books_or_str}<br>"
        f"books_range_str: <br>{books_range_str}"
        f"books_not_str: <br>{books_not_str}",
        content_type="text/html; charset=utf-8"
    )
    path('searchByq', views.searchByq, name='searchByq'),

訪問鏈接http://127.0.0.1:8000/article/searchByq

到此這篇關(guān)于Django 聚合查詢的文章就介紹到這了,更多相關(guān)Django 聚合查詢內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • python-docx讀取模板文檔并填充數(shù)據(jù)

    python-docx讀取模板文檔并填充數(shù)據(jù)

    python-docx?是開源的一個?Python?庫,用于讀取、創(chuàng)建和更新Microsoft?Word?2007+(.docx)文件,下面我們就來看看如何利用python-docx讀取模板文檔并填充數(shù)據(jù)吧
    2024-11-11
  • Python腳本實現(xiàn)自動化處理Excel選擇題

    Python腳本實現(xiàn)自動化處理Excel選擇題

    本文介紹了一個自動整理選擇題的Python腳本,可以將秒鐘自動將雜亂的試題題題庫整理成Excel表格格式,文中的示例代碼講解詳細,感興趣的小伙伴可以了解下
    2026-05-05
  • ubuntu22.04將python源切換為清華源的方法

    ubuntu22.04將python源切換為清華源的方法

    在使用pip命令安裝python的一些庫時,由于默認服務(wù)器在國外,因此下載需要很長時間,本文主要介紹了ubuntu22.04將python源切換為清華源的方法,感興趣的可以了解一下
    2023-12-12
  • python 接口實現(xiàn) 供第三方調(diào)用的例子

    python 接口實現(xiàn) 供第三方調(diào)用的例子

    今天小編就為大家分享一篇python 接口實現(xiàn) 供第三方調(diào)用的例子,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2019-08-08
  • 程序員寫Python時的5個壞習(xí)慣,你有幾條?

    程序員寫Python時的5個壞習(xí)慣,你有幾條?

    這篇文章主要介紹了程序員寫Python時的5個壞習(xí)慣,你有幾條?有的習(xí)慣會讓 Bug 變得隱蔽難以追蹤,當(dāng)然,也有的并沒有錯誤,只是個人覺得不夠優(yōu)雅。本文有示例代碼,感興趣的朋友跟隨小編一起看看吧
    2018-11-11
  • 如何基于opencv實現(xiàn)簡單的數(shù)字識別

    如何基于opencv實現(xiàn)簡單的數(shù)字識別

    現(xiàn)在很多場景需要使用的數(shù)字識別,比如銀行卡識別,以及車牌識別等,在AI領(lǐng)域有很多圖像識別算法,大多是居于opencv 或者谷歌開源的tesseract 識別,下面這篇文章主要給大家介紹了關(guān)于如何基于opencv實現(xiàn)簡單的數(shù)字識別,需要的朋友可以參考下
    2021-09-09
  • Django中select_related和prefetch_related的用法與區(qū)別詳解

    Django中select_related和prefetch_related的用法與區(qū)別詳解

    在實際的開發(fā)中,模型之間經(jīng)常存在復(fù)雜的關(guān)聯(lián)關(guān)系,下面這篇文章主要給大家介紹了關(guān)于Django中select_related和prefetch_related的用法與區(qū)別的相關(guān)資料,需要的朋友可以參考下
    2022-11-11
  • Python封裝原理與實現(xiàn)方法詳解

    Python封裝原理與實現(xiàn)方法詳解

    這篇文章主要介紹了Python封裝原理與實現(xiàn)方法,結(jié)合實例形式較為詳細的分析了Python封裝的概念、原理、實現(xiàn)方法及相關(guān)操作注意事項,需要的朋友可以參考下
    2018-08-08
  • 解決python opencv無法顯示圖片的問題

    解決python opencv無法顯示圖片的問題

    今天小編就為大家分享一篇解決python opencv無法顯示圖片的問題,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2018-10-10
  • Python編程中的文件讀寫及相關(guān)的文件對象方法講解

    Python編程中的文件讀寫及相關(guān)的文件對象方法講解

    這篇文章主要介紹了Python編程中的文件讀寫及相關(guān)的文件對象方法講解,其中文件對象方法部分講到了對文件內(nèi)容的輸入輸出操作,需要的朋友可以參考下
    2016-01-01

最新評論

和顺县| 益阳市| 巧家县| 舒城县| 鲁山县| 九寨沟县| 太仓市| 和龙市| 泾阳县| 九寨沟县| 湘阴县| 乐亭县| 平塘县| 龙井市| 泊头市| 石屏县| 五河县| 吴桥县| 湖州市| 安化县| 昭通市| 崇信县| 萍乡市| 德阳市| 万全县| 盐城市| 宜章县| 厦门市| 海伦市| 瓦房店市| 沭阳县| 友谊县| 东安县| 荆门市| 托克逊县| 阜南县| 东乌珠穆沁旗| 高邑县| 凤山市| 澄江县| 五华县|