What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

iTechGuides is reader-supported. When you buy through links on our site, we may earn an affiliate commission. As an Amazon Associate I earn from qualifying purchases. Learn more

Use django-query-guard to make Django tests fail when a code path exceeds a query budget or repeats the same normalized query. Install the released package, mark a database-backed pytest test with @pytest.mark.django_db and @pytest.mark.query_guard, and exercise the view or function that accesses related objects. Then fix the repeated lookups with select_related() or prefetch_related(), as appropriate.

Install django-query-guard

Install the released package from PyPI:

pip install django-query-guard

PyPI lists version 0.2.1, uploaded August 7, 2026. Check the package’s stated metadata against the Django and Python versions used by your project; classifiers are useful compatibility clues, not a guarantee for every environment. django-query-guard on PyPI · Version 0.2.1 release details.

Set a query budget in a pytest test

Use both markers on a test that needs database access. Set max_queries to a ceiling appropriate for the operation being tested, and enable repeated-query detection:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
import pytest

@pytest.mark.django_db
@pytest.mark.query_guard(max_queries=10, detect_n_plus_one=True)
def test_order_list_page(client):
    # Create the orders and related records needed by this test.
    response = client.get("/orders/")
    assert response.status_code == 200

The value 10 is an example budget, not a recommended universal limit. Choose a ceiling that fits the endpoint’s expected work, then keep the test in CI so later changes are checked as part of the normal test run. The package documents a configurable n_plus_one_threshold, with a default of 2 for release 0.2.1; adjust it only if the project’s behavior calls for a different threshold. See the package usage documentation.

Test the access pattern that triggers the queries

A test that only constructs a queryset may not reproduce the repeated database access. Exercise the operation that consumes it: request the endpoint, render the template, serialize the response, or iterate through the objects and read the related fields the application actually uses. For instance, if an order list displays each order’s customer name, the test should request or render that list rather than merely asserting that an order queryset exists.

The package also documents using query_guard(...) as a context manager around a specific code path, which can be useful when testing a task, management command, or view without decorating the whole test. Consult its PyPI documentation for the supported usage.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Fix repeated relation lookups

When the guard reports repeated queries, trace them to the relation being accessed and load that relation in a way suited to its type:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Relation being accessed Typical fix How it loads data
Foreign key or one-to-one select_related("customer") Fetches related rows through a SQL join as part of the original query.
Reverse foreign key or many-to-many prefetch_related("items") Fetches related rows separately and joins them to the objects in Python.

For example, if a page displays the customer for every order, update the queryset to load that foreign-key relation:

orders = Order.objects.select_related("customer")

If it displays each order’s line items, prefetch the reverse relation instead:

orders = Order.objects.prefetch_related("items")

Use the actual relation names from your models. These methods address common N+1 patterns; they do not guarantee that every query-count failure is an N+1 issue. Review the reported repeated query and the code path before changing the queryset.

Best Value

Keep the regression check useful

  • Set the budget for the tested operation, not for the whole application. A low ceiling that ignores legitimate setup or endpoint work can make the test brittle.
  • Keep test data and exercised behavior representative enough to trigger access to the related fields.
  • When a test fails, distinguish a repeated normalized query from a total-query-budget breach; they point to different issues.
  • Run the test in CI so a later template, serializer, or view change that reintroduces repeated relation access is caught.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.