주석처리를 바꿔주면서 결과를 확인해주면 된다.
# articles > templates > articles > index_1.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h1>Articles</h1>
{% for article in articles %}
<p>제목 : {{ article.title }}</p>
{% comment %} <p>댓글개수 : {{ article.comment_set.count }}</p> {% endcomment %}
<p>댓글개수 : {{ article.comment__count }}</p>
<hr>
{% endfor %}
</body>
</html>
# articles > views.py
더보기
from django.shortcuts import render
from .models import Article, Comment
from django.db.models import Count
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)
def index_2(request):
# articles = Article.objects.order_by('-pk')
articles = Article.objects.select_related('user').order_by('-pk')
context = {
'articles': articles,
}
return render(request, 'articles/index_2.html', context)
def index_3(request):
# articles = Article.objects.order_by('-pk')
articles = Article.objects.prefetch_related('comment_set').order_by('-pk')
context = {
'articles': articles,
}
return render(request, 'articles/index_3.html', context)
from django.db.models import Prefetch
def index_4(request):
# articles = Article.objects.order_by('-pk')
# articles = Article.objects.prefetch_related('comment_set').order_by('-pk')
articles = Article.objects.prefetch_related(
Prefetch('comment_set', queryset=Comment.objects.select_related('user'))
).order_by('-pk')
context = {
'articles': articles,
}
return render(request, 'articles/index_4.html', context)
'WEB > Django prac' 카테고리의 다른 글
[Django prac][json응답연습] 2. 데이터 응답받기 (0) | 2024.04.14 |
---|---|
[Django prac][Improve query] 5. 최적화 (0) | 2024.04.13 |
[Django prac][Improve query] 3. 최적화 이론 설명 (0) | 2024.04.12 |
[Django prac][Improve query] 2. 최적화 (0) | 2024.04.12 |
[Django prac][Improve query] 1. 최적화 (0) | 2024.04.12 |