Explore my side projects and work using this link

Upsidedown is a WordPress theme design that brings blog posts rising above inverted header and footer components.

Woman showing board with inscription against bottles with pumps in eco shop
Advertisements

쿼리 수를 줄이기 위해 Foreign Key 가 포함된 테이블, 모델에서는 join 을 써야 한다.

헷갈리는 거니깐, 정리해 둔 글을 보자.

[Django] 간단하게 알아보는 N+1 문제 해결! (select_related, prefetch_related)

prefetch_related와 select_related의 차이점은 prefetch_related는 select_related 처럼 조인을 하는게 아니라, 필터링을 한다는 점입니다. 즉, Post에서 id를 쭉 불러오고, 이를 tag에서 필터링한다는 점이 select_related와의 차이점 입니다. 다만, 여기서 tag에서 post_id로 필터링 하려면, tag와 tag_set이 조인된 테이블이 필요하기 때문에 조인이 일어납니다.

https://bio-info.tistory.com/174
for comment in Comment.objects.all().select_related("post"):
    print(comment.post.title)

post 라는 필드는 Post 라는 테이블을 Foreign key 로 Comment 오브젝트에 선언되어 있다.

용례만 알면 되지 🙂

암튼 HTML 템플릿에서 리스트 수 만큼 쿼리가 수행되던 것이 확 줄어 버리게 된다.

외부 키로 값을 가져오는 경우에는 반드시 select_related 를 선언해서 SQL 수를 줄이자!

Woman showing board with inscription against bottles with pumps in eco shop

참고사이트

[Django] 테이블(모델)의 JOIN(3) ; prefetch_related() – https://engineer-mole.tistory.com/147

Advertisements