Skip to main content

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

  • Python 3.9+
  • uv (for dependency management)
  • just (optional, for task running)

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

  1. Create a branch from main.
  2. Make your changes.
  3. Run just pre_commit to verify formatting, linting, and tests pass.
  4. 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


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

show_db_queries-1.0.1.tar.gz (7.3 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

show_db_queries-1.0.1-py3-none-any.whl (8.6 kB view details)

Uploaded Python 3

File details

Details for the file show_db_queries-1.0.1.tar.gz.

File metadata

  • Download URL: show_db_queries-1.0.1.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

Hashes for show_db_queries-1.0.1.tar.gz
Algorithm Hash digest
SHA256 14593f10f8ecd67ef26d21a22c94a0c74b27e546969784f4a0838396d1481e64
MD5 35e35ca749877a0cfe8550724f753652
BLAKE2b-256 5b14a277db8513e1832ec5976bae30028cb3385d67242bee824b6cb8745220a3

See more details on using hashes here.

File details

Details for the file show_db_queries-1.0.1-py3-none-any.whl.

File metadata

  • Download URL: show_db_queries-1.0.1-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

Hashes for show_db_queries-1.0.1-py3-none-any.whl
Algorithm Hash digest
SHA256 83b7bc54bd0aa2e971d4a98b600a90da4d842e3d1b5c3ab9819faf13c768bf6c
MD5 7890103e2de7a6aea69ae8f3f532e5e8
BLAKE2b-256 e1b42a3f401ebdb60e3375a84200b86e590459add20638088d816effa20ea250

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page