码迷,mamicode.com
首页 > 其他好文 > 详细

django数据查询优化annotate和aggregate

时间:2016-09-08 16:38:02      阅读:629      评论:0      收藏:0      [点我收藏+]

标签:django   annotate   aggregate   

from django.db.models import Count

Device.objects.extra({‘install_data‘:"date(create_time)"}).values(‘install_data‘).annotate(count=Count(‘id‘))


django 中 annotate和aggregate的区别:


aggregate 计算整个queryset的值,相当于count(). Annotate 对于 queryset 中的每个值在指定的属性上进行汇总,相当于group_by.


aggregation

>>> Book.objects.aggregate(average_price=Avg(‘price‘))

{‘average_price‘: 34.35}

返回一个包含所有书价的平均值字典


Annotation

>>> q = Book.objects.annotate(num_authors=Count(‘authors‘))

>>> q[0].num_authors

2

>>> q[1].num_authors

1

q是books的queryset, 但是每本书按照作者的数量进行了聚合.


本文出自 “Linux运维” 博客,请务必保留此出处http://utrace.blog.51cto.com/2213120/1850610

django数据查询优化annotate和aggregate

标签:django   annotate   aggregate   

原文地址:http://utrace.blog.51cto.com/2213120/1850610

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