首页 > 代码库 > 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