073:【Django数据库】ORM聚合函数详解-Count

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

实例截图如下:

猜你喜欢

转载自www.cnblogs.com/zheng-weimin/p/10246904.html
今日推荐