使用Django的ORM建立了如下Model:
class Book(models.Model): # 书籍名字 name = models.CharField(max_length=300) # 书籍页数 pages = models.IntegerField() # 书籍价格 price = models.DecimalField(max_digits=10, decimal_places=2) # 书籍作则 authors = models.CharField(max_length=300) publisher = models.CharField(max_length300) # 发布日期 pub_date = models.DateField()
现在想查询以字段authors分组,查出每个作者所著所有书的总页书,用SQL语句可以很容易的完成此任务:
SELECT *, SUM(pages) AS total_pages FROM Book GROUP BY authors;
那么如何用Django自带的ORM接口实现呢?
方法如下:
from django.db.models import Sum result = Book.objects.values("authors").annotate(total_pages=Sum("pages")).all()
计算每个作者一共写了多少本书籍代码示例:
from django.db.models import Count result = Book.objects.values("authors").annotate(total=Count("name ")).all()
计算书籍的平均价格代码示例:
from django.db.models import Avg result = Book.objects.values("authors").annotate(price=Avg("price ")).all()
参考文献:
http://www.chenxm.cc/post/465.html