2016-09-29 64 views
1

我讀的annotating and aggregating的開端,我不知道哪條路是最好的完成情況如下:簡單的Django聚合 - 優化

你要算作家的數量爲每本書在一個查詢集。本教程建議用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

因爲那樣的話,你將不得不查詢模型:

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

然後調用count() - 一旦你對多個對象(書),你會打DB每個你打電話count()本書做到這一點!

使用annotate時,您只會敲擊一次數據庫,並將查詢結果作爲字典/列表全部查詢中的書籍。