我正在阅读注释和聚合的开始,我想知道哪种方式最适合完成以下情况:
您想计算查询集中每本书的作者数量。本教程建议以下内容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 %}
一种情况比另一种更好吗?我缺少优化的好处吗?