ORM聚合函數詳解-Count:
Count :獲取指定的對象的個數。示例代碼如下:
from django.db.models import Count result = Book.objects.aggregate(book_num=Count('id'))
以上的 result 將返回 Book 表中總共有多少本圖書。
Count 類中,還有另外一個參數叫做 distinct ,默認是等於 False ,如果是等於 True ,那么將去掉那些重復的值。比如要獲取作者表中所有的不重復的郵箱總共有多少個,那么可以
通過以下代碼來實現:
from djang.db.models import Count result = Author.objects.aggregate(count=Count('email',distinct=True))
獲取每種數買了多少本:
result = Book.objects.annotate(book_type=Count("bookorder__id")) # bookorder__id 和 bookorder 一樣(如果是主鍵) print(result) for item in result: print(item.name, item.book_type) print(result.query)
SELECT `book`.`id`, `book`.`name`, `book`.`pages`, `book`.`price`, `book`.`rating`, `book`.`author_id`, `book`.`publisher_id`, COUNT(`book_order`.`id`) AS `book_type` FROM `book` LEFT OUTER JOIN `book_order` ON (`book`.`id` = `book_order`.`book_id`) GROUP BY `book`.`id` ORDER BY NULL
實例截圖如下:

