본문 바로가기

advanced/웹 - 백엔드

[Django] pytest에서 ORM의 실제 query 확인하기

예를 들어서 다음과 같은 ORM이 있다고 했을 때,

Model.objects.create(a=1, b=2)

 

실제 나가는 쿼리를 pytest에서 확인하려면, pytest 코드 안에 다음과 같은 with절 이하를 집어넣으면 확인할 수 있습니다.

from django.db import connection
from django.test.utils import CaptureQueriesContext

with CaptureQueriesContext(connection) as ctx:
    loaded_cart = db_cart_loader.load(request_dto)
    print(ctx.captured_queries)

위와 같이 실제 쿼리 나가는 것을 확인할 수 있습니다.

 

pytest환경이 아닌 실행 중에 확인하려면, 아래와 같이 확인 가능합니다.

- python manage.py shell_plus --print-sql

- python manage.py runserver_plus --print-sql