码迷,mamicode.com
首页 > 数据库 > 详细

075: 【Django数据库】ORM聚合函数详解-Sum

时间:2019-01-09 23:34:31      阅读:349      评论:0      收藏:0      [点我收藏+]

标签:添加   官方   col   技术分享   ref   result   com   queryset   销售   

ORM聚合函数详解-Sum:

Sum :求指定对象的总和。比如要求图书的销售总额。那么可以使用以下代码实现:

from djang.db.models import Sum
result = Book.objects.annotate(total=Sum("bookstore__price")).values("name","total")

以上的代码 annotate 的意思是给 Book 表在查询的时候添加一个字段叫做 total ,这个字段的数据来源是从 BookStore 模型的 price 的总和而来。 values 方法是只提取 name 和 total 两个字段的值。

不多说了,直接上代码吧:

# views.py内容:
def index(request):
    # 所有书的销售总额:
    # total = BookOrder.objects.aggregate(total=Sum("price"))
    # print(total)
    # 每种书的销售总额:
    # books = Book.objects.annotate(total=Sum("bookorder__price"))
    # for item in books:
    #     print(item.name, item.total)
    # print(books.query)
    # 求2019年度销售总额:
    # total = BookOrder.objects.filter(create_time__year=2019).aggregate(sum=Sum("price"))
    # print(total)
    # 求2019年每种书的度销售总额:
    total = Book.objects.filter(bookorder__create_time__year=2019).annotate(sum=Sum("price"))
    for item in total:
        print(item.name, item.sum)
    print(total.query)
    return HttpResponse("success")

 实例截图如下:

技术分享图片

 更多的聚合函数请参考官方文

档:https://docs.djangoproject.com/en/2.0/ref/models/querysets/#aggregation-functions

075: 【Django数据库】ORM聚合函数详解-Sum

标签:添加   官方   col   技术分享   ref   result   com   queryset   销售   

原文地址:https://www.cnblogs.com/zheng-weimin/p/10247332.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!