A lightweight context manager to print and inspect Django DB queries during development and tests.
Project description
show-db-queries
A lightweight context manager to print and inspect Django database queries during development and tests. Debug query issues without the overhead of Django Debug Toolbar or Silk, with granular control over exactly which code blocks you want to inspect.
Installation
pip install show-db-queries
# or
uv pip install show-db-queries
Compatibility
| Supported versions | |
|---|---|
| Python | 3.9 – 3.13 |
| Django | 4.2, 5.0, 5.1, 5.2 |
Quickstart
Wrap any code block to see every SQL query it executes:
from show_db_queries import show_queries
with show_queries():
User.objects.filter(is_active=True)
Output:
Queries:
0. 0.042 ms
--------------------------------------------------------------------------------
SELECT "auth_user"."id", "auth_user"."username", ...
FROM "auth_user"
WHERE "auth_user"."is_active" = true;
Queries executed: 1
Usage
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
connection |
Django connection | None |
Database connection to monitor. Defaults to DEFAULT_DB_ALIAS. |
print |
bool |
True |
Print queries to stdout when the block exits. |
color |
bool |
True |
Syntax-highlight SQL with ANSI colors for terminal output. |
file |
str |
None |
Write queries to a file in SQL comment format (colors disabled in file). |
stacktrace |
bool |
False |
Attach Python stacktraces to each query for source attribution. |
threshold |
float |
None |
Only show queries taking >= this many milliseconds. |
The previous long parameter names (db_connection, print_queries, colorize, file_path, include_stacktrace, query_time_threshold) are still accepted for backward compatibility.
Capture queries silently
Disable printing and access results programmatically:
ctx = show_queries(print=False)
with ctx:
User.objects.create(username="test")
formatted_sql = ctx.get_queries(colorize=False)
print(f"Total queries: {ctx.final_queries}")
Monitor a specific database connection
from django.db import connections
replica = connections["replica"]
with show_queries(connection=replica):
User.objects.using("replica").all()
Write queries to a file
Queries are written in SQL format with comments for easy reading:
with show_queries(file="/tmp/queries.sql"):
Order.objects.select_related("customer").filter(status="pending")
Include stacktraces
Find exactly where each query originates in your code:
with show_queries(stacktrace=True):
User.objects.get(pk=1)
Output includes the Python call stack for each query:
0. 0.035 ms
--------------------------------------------------------------------------------
SELECT ... FROM "auth_user" WHERE "auth_user"."id" = 1;
File "myapp/views.py", line 42, in get_user
User.objects.get(pk=1)
Filter slow queries
Only display queries above a time threshold (in milliseconds):
with show_queries(threshold=50.0):
# Only queries taking >= 50ms will appear
process_large_dataset()
Spot N+1 query problems
Compare query counts before and after optimization:
# Before: N+1 queries
with show_queries():
for book in Book.objects.all():
print(book.author.name)
# Queries executed: 101
# After: single query with join
with show_queries():
for book in Book.objects.select_related("author"):
print(book.author.name)
# Queries executed: 1
Use in tests
class TestOrderCreation(TestCase):
def test_query_count(self):
ctx = show_queries(print=False)
with ctx:
create_order(user=self.user, item=self.item)
self.assertLessEqual(ctx.final_queries, 3)
Django settings
Set project-wide defaults so you don't have to pass the same options every time:
# settings.py
SHOW_DB_QUERIES = {
"file": "/tmp/queries.sql",
"color": False,
"stacktrace": True,
}
Any key matching a constructor parameter (print, color, file, stacktrace, threshold) can be included. Explicit arguments passed to ShowDBQueries() or show_queries() always take precedence over these defaults.
Optionally configure the Pygments color theme used for syntax highlighting:
# settings.py
CODE_FORMAT_STYLE = "monokai" # any Pygments style name
Contributing
Prerequisites
Local setup
git clone https://github.com/levi/show-db-queries.git
cd show-db-queries
uv sync
Running tests
# Run all tests
uv run pytest
# Run with verbose output
uv run pytest -v
# Run a specific test
uv run pytest tests/test_context_managers.py::TestShowDBQueries::test_query
# Run with coverage report
uv run pytest --cov --cov-config=pyproject.toml --cov-report=html
open htmlcov/index.html
Or using just:
just test
just test -v
just test_with_coverage
Linting and formatting
# Lint
uv run ruff check
# Format
uv run ruff format
# Run all checks (format + lint + test)
just pre_commit
Making changes
- Create a branch from
main. - Make your changes.
- Run
just pre_committo verify formatting, linting, and tests pass. - Submit a pull request.
Releasing
Versioning and publishing is handled via the justfile and GitHub Actions:
just version_bump patch # or minor, major
git push --follow-tags
Then create a release on GitHub to trigger the PyPI publish workflow.
License
MIT
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file show_db_queries-1.0.0.tar.gz.
File metadata
- Download URL: show_db_queries-1.0.0.tar.gz
- Upload date:
- Size: 7.3 kB
- Tags: Source
- Uploaded using Trusted Publishing? Yes
- Uploaded via: uv/0.10.4 {"installer":{"name":"uv","version":"0.10.4","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
eb678e4fe4ad36a1800b749be26d1910483f9c57571f24330b7e1c3344e5dad0
|
|
| MD5 |
abb7a74081bb3836b9c8c86ce551dfb9
|
|
| BLAKE2b-256 |
e6175e492d4557afe7fc1b33ce683ff318f3b1ae77928e79baf8e55fd84766a8
|
File details
Details for the file show_db_queries-1.0.0-py3-none-any.whl.
File metadata
- Download URL: show_db_queries-1.0.0-py3-none-any.whl
- Upload date:
- Size: 8.6 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? Yes
- Uploaded via: uv/0.10.4 {"installer":{"name":"uv","version":"0.10.4","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
7ef6aa5662281de75ebe7ae2cb9723429f78a43212cd3fc59fca96eeb153fb94
|
|
| MD5 |
cca95adc3a0d1e1b5a9bbe91bbc7736e
|
|
| BLAKE2b-256 |
5edc1de677c7eb326433f1f23a3d44abf9f8cedef9a70a6bf23397a722666b9c
|