Nur*_*fat 2 python django orm aggregate django-orm
这里我们使用聚合计算
>>> avg = Book.objects.aggregate(average_price=Avg('price'))
{'average_price': 34.35}
Run Code Online (Sandbox Code Playgroud)
但是为什么我们不在上面使用下面的概念。
a = Books.objects.all()
Avg = sum([x.price for x in a])/len(a)
34.35
Run Code Online (Sandbox Code Playgroud)
我想知道使用聚合而不是第二个过程。
Book.objects.aggregate(average_price=Avg('price'))- 这将转换为等效的 SQL 查询并在数据库上执行并直接获取聚合数据。这更快。
而使用第二种方法
sum()然后计算价格总和a使用的长度,len()然后第二种方法比第一种方法有更多的开销,因为涉及函数调用、执行除法、将对象加载到列表等,
| 归档时间: |
|
| 查看次数: |
76 次 |
| 最近记录: |