首页 > 代码库 > django数据查询优化annotate和aggregate
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
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。