Django : N+1 Problem

Seoyul Kim·2020년 8월 5일
0

Django

목록 보기
11/12

Django의 ORM은 Lazing-Loading 방식인데, 이 방식을 사용하면 ORM에서 명령을 실행할 때마다 데이터베이스에서 데이터를 가져오는 것이 아니라, 모든 명령 처리가 끝나고 실제로 데이터를 불러와야 할 시점에 데이터베이스에 쿼리를 실행한다.

def myview(request):
    # Query the database
    books = Book.objects.all()

    for book in books:
        # Query the database on each iteration to get author (len(books) times)
        # if there is 100 books, there will have 100 queries plus the initial query
        book.author
        # ...

    # total : 101 queries

N+1 problem은 쿼리 1번으로 N건의 데이터를 가져왔는데, 원하는 데이터를 얻기 위해 이 N건의 데이터를 데이터 수만큼 반복해서 2차적으로 쿼리를 수행하는 문제이다. 이 방식은 Eager-Loading 방식으로 해결할 수 있는데, Eager-Loading은 사전에 쓸 데이터를 포함하여 쿼리를 날리기 때문에 비효율적으로 늘어나는 쿼리 요청을 방지할 수 있다.(prefetched_related, select_related)

# views.py
def myview(request):
    # Query the database.
    books = Books.objects.select_related('author').all()
    
    for book in books:
        # Does not query the database again, since `author` is pre-populated
        book.author
        # ...

    # total : 1 query

0개의 댓글