Skip to main content

django-traceback-in-sql

Test Suite Ruff uv

PyPi Version image Supported Python Versions Supported Django versions

Annotates the stacktrace into the SQL query as a comment at runtime. Helpful for tracking down where queries are ran from within code, for example for analysing query counts in unit tests when trying to prevent N+1s.

Compatibility

  • Python 3.9–3.13
  • Django 4.2, 5.2
  • SQLite, PostgreSQL, MySQL

Quick Examples

Find N+1 queries in Django unit tests

from django.contrib.auth import get_user_model
from django.test import TestCase
from sql_traceback import sql_traceback


User = get_user_model()


class Test(TestCase):
    def test_something(self):
        with sql_traceback(), self.assertNumQueries(0):
            _ = User.objects.count()

If the assert gets triggered, you will see something like the following output:

E   AssertionError: 1 != 0 : 1 queries executed, 0 expected
E   Captured queries were:
E   1. SELECT COUNT(*) AS `__count` FROM `auth_user`
E   /*
E   STACKTRACE:
E   # /path/to/tests/test_test_test.py:12 in test_something
E   */

In pytest-django tests

The above equivalent would look like so

import pytest
from django.contrib.auth import get_user_model
from sql_traceback import sql_traceback


User = get_user_model()


@pytest.mark.django_db
def test_something(django_assert_num_queries):
    with sql_traceback(), django_assert_num_queries(0):
        _ = User.objects.count()

and when pytest is ran with the -v flag, you will see the following in the output

E               Queries:
E               ========
E
E               SELECT COUNT(*) AS `__count` FROM `auth_user`
E               /*
E               STACKTRACE:
E               # /path/to/tests/tests/test_test_test.py:12 in test_something
E               */

As a context manager

from django.db import connection
from sql_traceback import sql_traceback
from services import get_user_count

with sql_traceback():
    get_user_count()

print(connection.queries[-1]['sql'])

Should print output

SELECT COUNT(*) AS "__count" FROM "auth_user"
/*
STACKTRACE:
# /path/to/project/services.py:5 in get_user_count
*/

As a decorator

from sql_traceback import SqlTraceback

@SqlTraceback()
def get_users():
    return User.objects.filter(is_active=True)

Configuration

Optional settings in your Django settings.py:

SQL_TRACEBACK_ENABLED = True                      # Enable/disable stacktracing (default: True)
SQL_TRACEBACK_MAX_FRAMES = 15                     # Max number of stack frames (default: 15)
SQL_TRACEBACK_FILTER_SITEPACKAGES = True          # Filter out third-party packages (e.g., **django**, requests, pluggy, etc.) (default: True)
SQL_TRACEBACK_FILTER_TESTING_FRAMEWORKS = True    # Filter out pytest/unittest frames (pytest + unittest) (default: True)
SQL_TRACEBACK_FILTER_STDLIB = True                # Filter out Python standard library frames (e.g., threading, contextlib, etc.) (default: True)
SQL_TRACEBACK_MIN_APP_FRAMES = 1                  # Minimum application frames required (default: 1)

Metadata

Release files for django-traceback-in-sql 0.2.3

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for django-traceback-in-sql 0.2.3
File Size Uploaded Provenance
django_traceback_in_sql-0.2.3.tar.gz 27.0 kB Without provenance Details

Built distribution (wheel)

Table of built distributions (wheels) for django-traceback-in-sql 0.2.3
File Interpreter ABI Platform
django_traceback_in_sql-0.2.3-py3-none-any.whl Python 3 none any Details

Total release size: 59.0 kB

Release files / django_traceback_in_sql-0.2.3.tar.gz

Download URL django_traceback_in_sql-0.2.3.tar.gz
Size 27.0 kB
Tags Source
SHA-256 checksum
How to use checksums
f2211b7b0fcfe989714f597e732b5e9c3a876f675c142fa327e2070b6e2307e5
BLAKE2b-256 checksum
How to use checksums
50a156e6286dbb52a8d158e6ba87b88c964c31b2687571e09a3affbbe5ffc203
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via uv/0.9.5

Release files / django_traceback_in_sql-0.2.3-py3-none-any.whl

Download URL django_traceback_in_sql-0.2.3-py3-none-any.whl
Size 32.1 kB
Tags Python 3
SHA-256 checksum
How to use checksums
67cc78b36dd082c13fb698b5c2066182913f2f05a944fafdc461bbf7bed9a7cb
BLAKE2b-256 checksum
How to use checksums
5503829d5e2a5e5d6f6cb8c25cfe928eba0ad3942df70ff409e7eb81a3286ee4
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via uv/0.9.5

Security for django-traceback-in-sql 0.2.3

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page