DB
DB에 대하여(22)_annotate (feat. Django)
데이터분석가 이채은
2024. 5. 9. 23:16
annotate
SQL의 GROUP BY 쿼리를 사용합니다.
문제 상황
annotate 적용
문제를 해결해 봅시다.
게시글을 조회하면서 댓글 개수까지 한 번에 조회해서 가져옵니다.
# views.py
def index_1(request):
# articles = Article.objects.order_by('-pk')
articles = Article.objects.annotate(Count('comment')).order_by('-pk')
context = {
'articles': articles,
}
return render(request, 'articles/index_1.html', context)
<!-- index_1.html -->
<p>댓글 개수 : {{ article.comment__count }}</p>
"11 queries including 10 similar" → "1 query"