GROUB BY ... COUNTSUM Django ORM 等价物
我们可以在 Django ORM 上执行 GROUP BY ... COUNT 或 GROUP BY ... SUM SQL 等价查询,分别使用 annotate(),values(),order_by() 和 django.db.models 的 Count 和 Sum 方法:
让我们的模型是:
   class Books(models.Model):
       title  = models.CharField()
       author = models.CharField()
       price = models.FloatField()
GROUP BY ... COUNT :
- 
让我们假设我们想要计算
Books表中每个不同作者存在多少个书对象:result = Books.objects.values('author') .order_by('author') .annotate(count=Count('author')) - 
现在
result包含一个包含两列的查询集:author和count:author | count ------------|------- OneAuthor | 5 OtherAuthor | 2 ... | ... 
GROUB BY ... SUM :
- 
让我们假设我们想要总结我们的
Books表中存在的每个不同作者的所有书籍的价格:result = Books.objects.values('author') .order_by('author') .annotate(total_price=Sum('price')) - 
现在
result包含一个包含两列的查询集:author和total_price:author | total_price ------------|------------- OneAuthor | 100.35 OtherAuthor | 50.00 ... | ...