WEB/Django prac

[Django prac][Improve query] 4. 최적화

bay07 2024. 4. 12. 23:56

주석처리를 바꿔주면서 결과를 확인해주면 된다. 

 

# 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)