본문 바로가기

프로그래밍/Python

[Python|Django] 장고(django)에서 백만건을 가져오는 queryset이 느리다.

반응형

장고(django)에서 백만건을 가져오는 queryset이 느리다.


https://stackoverflow.com/questions/43540295/get-million-record-from-django-with-queryset-is-slow


질문 :


다음 코드처럼 Post 테이블의 모든 오브젝트를 가져와 이터레이트하려 한다.


    posts = Post.objects.all()

    

    for post in posts:

        process_post(post)


process_post 는 백그라운드에서 동작하며, update 는 하지 않는 셀러리태스크이다.

그런데, Post 테이블에 100만개의 레코드가 있어서 문제다. 이 동작은 매일 수행된다.


    for post in posts:


코드 중 위 라인 부분에서 데이터베이스 Query 가 수행되어 DB에서 모든 데이터를 한꺼번에

가져온다.


성능을 어떻게 향상시킬 수 있을까? 







자신만의 이터레이터 레이어를 만들어 보라.


count = Post.objects.all().count() # 100 만

chunk_size = 1000

for i in range(0, count, chunk_size):

    posts = Post.objects.all()[i:i+chunk_size]

    for post in posts:

        process_post(post)


queryset 에 대한 슬라이싱은 "LIMIT", "OFFSET" query로 변환되 수행된다.

chunk_size 가 커질수록, query 횟수는 작아지고, 메모리사용량은 커질 것이다.

자신의 use case 에 맞도록 chunk_size 를 적절히 조정하라.



728x90