简单的Django聚合 - 优化

时间:2016-09-29 22:07:24

标签: django django-queryset django-aggregation

我正在阅读annotating and aggregating的开头,我想知道哪种方式最适合完成以下情况:

您想要计算查询集中每本书的作者数量。本教程使用annotate建议以下内容:

Book.objects.annotate(Count('authors'))

我的问题是,为什么这样做可以用模型实例方法完成:

#models.py
class Book(models.Model):
  authors = models.ManyToManyField(Author)

  def author_count(self):
    return self.authors.count()

#views.py
books = Book.objects.all()

#template.html
{% for book in books %}
  {{ book.author_count }}
{% endfor %}

一种情况比另一种情况好吗?我是否缺少优化优势?

1 个答案:

答案 0 :(得分:1)

因为那时您将不得不查询模型:

Books.objects.all()  # Or any other filter

然后你致电count() - 一旦你为多个对象(书籍)做了这样的话,你就会为你拨打count()的每本书点击数据库!

使用annotate时,您只会点击一次数据库,并将结果作为查询中所有书籍的词典/列表。