Skip to main content

Command Palette

Search for a command to run...

About CaptureQueriesContext

Published
View as Markdown

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.

1.0K views

More from this blog

T

Today I Learned

12 posts

I am a software engineer at Chromatic, doing back end work in Go and TypeScript. If you want to learn more about me, check out my portfolio.