#views.py
def index_2(request):
articles = Article.objects.order_by('-pk')
context = {
'articles': articles,
}
return render(request, 'articles/index_2.html', context)
#templates/index_2.html
{% block content %}
<h1>Articles</h1>
{% for article in articles %}
<h3>작성자 : {{ article.user.username }}</h3>
<p>제목 : {{ article.title }}</p>
<hr>
{% endfor %}
{% endblock content %}
def index_2(request):
#article을 가져올 때 user까지 결과에 추가한다.
articles = Article.objects.select_related('user').order_by('-pk')
context = {
'articles': articles,
}
return render(request, 'articles/index_2.html', context)
#views.py
def index_3(request):
articles = Article.objects.order_by('-pk')
context = {
'articles': articles,
}
return render(request, 'articles/index_3.html', context)
#templates/index_3.html
{% block content %}
<h1>Articles</h1>
{% for article in articles %}
<p>제목 : {{ article.title }}</p>
<p>댓글 목록</p>
{% for comment in article.comment_set.all %}
<p>{{ comment.content }}</p>
{% endfor %}
<hr>
{% endfor %}
{% endblock content %}
def index_3(request):
# articles = Article.objects.order_by('-pk')
#article을 조회할 때 comment_set 역참조를 동시에 진행
articles= Article.objects.prefetch_related('comment_set')
context = {
'articles': articles,
}
return render(request, 'articles/index_3.html', context)
#views.py
def index_4(request):
articles = Article.objects.order_by('-pk')
context = {
'articles': articles,
}
return render(request, 'articles/index_4.html', context)
#templates/index_4.html
{% block content %}
<h1>Articles</h1>
{% for article in articles %}
<p>제목 : {{ article.title }}</p>
<p>댓글 목록</p>
{% for comment in article.comment_set.all %}
<p>{{ comment.user.username }} : {{ comment.content }}</p>
{% endfor %}
<hr>
{% endfor %}
{% endblock content %}
def index_4(request):
#처음에 comment_set 참조하고, user역참조 같이진행
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)
'작은 효율성에 대해서는, 말하자면 97%정도에 대해서는, 잊어버려라. 섣부른 최적화는 모든 악의 근원이다.'
Donald E. knuth