About CaptureQueriesContext
If you ever need to access the raw SQL executed during any unit test, the CaptureQueriesContext
context manager can help. It's very simple:
from django.db import connection
from django.test.utils import CaptureQueriesContext
def test_foo():
with CaptureQueriesContext(connection) as ctx:
# run some SQL queries
print(ctx.captured_queries)
# run assertions after printing if you want to guarantee that print fires
The output is a list of dictionaries of the form {"sql": "<SQL QUERY>"}
, so you can iterate over them, run assertions on them, pretty print them -- whatever you want.
Credit to this StackOverflow post.