DB
DB에 대하여(23)_select_related (feat. Django)
데이터분석가 이채은
2024. 5. 10. 09:00
select_related
SQL의 INNER JOIN 쿼리를 활용합니다. 1:1 또는 N:1 참조 관계에서 사용합니다.
문제 상황
select_related 적용
문제를 해결해 봅니다.
게시글을 조회하면서 유저 정보까지 한 번에 조회해서 가져옵니다.
# views.py
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)
"11 queries including 10 similar and 8 duplicates" → "1 query"