Comparison with other tools#

This page compares pytest-queryguard with other tools that look for N+1 queries or count queries. It is written by the author of pytest-queryguard, so read it with that in mind: the matrix is built from the competitors' own documentation and from running their packages, every cell says which, and the measurements are ones I ran myself, on scenarios I wrote.

In short: of the SQLAlchemy tools in the matrix, pytest-queryguard is the only one that fails tests with no marker, option or fixture, and the only one with a missing-index check beyond PostgreSQL (SQLite, MySQL and MariaDB). It reports Core and text() loops as well as lazy loads, lists every statement with its call site when a budget fails, and has a baseline and SARIF for adoption. These are the features of the current release; the measured runs are of the dated versions named below. queryspy is the closest alternative, with its own middleware and panel; pytest-querycount writes budgets into your tests; for Django, django-zeal is the established tool and pytest-queryguard covers it too (Django, no longer experimental since 1.1.0). The matrix, where the others are ahead and choosing have the details.

Who is who#

Tool Version (release date) First release on PyPI Targets License
pytest-queryguard 1.0.0 (2026-11-14) 2026-10-10 SQLAlchemy 2; Django (experimental until 1.1.0) MIT
queryspy 0.6.0 (2026-10-22) 2026-08-04 SQLAlchemy 2.0+, Python 3.11+ MIT
pytest-querycount 0.4.0 (2026-09-27) 2026-09-27 SQLAlchemy 2.x MIT
nplusone 1.0.0 (2018-05-21) 2015-06-30 Django, SQLAlchemy, Peewee MIT
nplus1 1.1.5 (2026-06-17) 2026-05-22 Django, SQLAlchemy, Flask-SQLAlchemy, Peewee, Celery; Python 3.11+ MIT
django-zeal 2.3.0 (2026-10-14) 2024-07-20 Django MIT
fastapi-nplusone 0.1.0 (2026-02-10) 2026-02-06 FastAPI with SQLAlchemy BSD-3-Clause
pytest-capquery 0.3.3 (2026-04-04) 2026-04-01 SQLAlchemy, Python 3.13+ CC BY-NC-SA 4.0 (see below)
django-nplus1 0.6.2 (2026-10-04) 2026-04-05 Django MIT
django-query-doctor 2.3.0 (2026-08-01) 2026-03-14 Django MIT
n-plus-one-sniffer not on PyPI (repository created 2026-07-18) not on PyPI SQLAlchemy 2.0+ MIT (repository)
orm-lens 1.18.1 (2026-11-17) 2026-07-12 as django-orm-lens, 2026-10-31 as orm-lens Django; SQLAlchemy models in preview since 2026-10-31 MIT

Release dates come from the PyPI JSON API on 2026-10-12, re-checked on 2026-10-13 and 2026-11-05; the rows of pytest-queryguard, django-nplus1, django-query-doctor and n-plus-one-sniffer were read on 2026-11-07 (PyPI and GitHub), the row of nplus1 on 2026-11-08. Every row was checked again on 2026-11-10 (PyPI, and GitHub for n-plus-one-sniffer, whose latest commit is still d4790f8): only pytest-queryguard had a new release. On 2026-11-14 (PyPI, and GitHub for n-plus-one-sniffer, still at d4790f8) only orm-lens (1.18.0, fixes to its Django model parser, its index suggestions and its factory generator) and pytest-queryguard (1.0.0) had. Most of these projects are young: pytest-queryguard, queryspy and pytest-querycount shipped their first release in the second half of 2026, so expect all of them to change. This table will be out of date; check the projects' own pages.

orm-lens is a different kind of tool: it reads the source of Django and SQLAlchemy models and the code that queries them (static analysis of the syntax tree, with no database and without starting the application), and has a command line and an MCP server for AI coding agents. Its nplusone command looks for N+1 patterns in the code; it does not run tests or watch the statements a test sends, so it is not in the matrix below. Read from its PyPI description on 2026-11-05, and again on 2026-11-14 for 1.18.0 (its SQLAlchemy support is still marked preview), not run. pytest-queryguard has an experimental static check of its own (since 0.8.0), which reads the mappers by importing your model modules and reports only lazy relationships read in a loop over a query inside one function, and an experimental MCP server, whose tools run the test suite and return the findings the tests produce. The two static checks were not compared.

Five tools are not in the matrix below. nplus1 was read and run on 2026-11-08. For three others, found on 2026-11-07, what follows was read in their READMEs on that date, and for redline in its README and documentation on 2026-11-14; none of them was run:

Django query counters and snapshots#

With Django no longer experimental in 1.1.0, these Django tools count, record or assert queries rather than look for N+1 by relationship. What follows was read in their PyPI descriptions and documentation on 2026-11-20 (versions and dates from the PyPI JSON API that day); none of them was run, and none is in the matrix.

Tool Version (release date) What it does
pytest-django's django_assert_num_queries 4.14.0 (2026-08-10) A fixture that asserts an exact (or, with django_assert_max_num_queries, a maximum) number of queries in a block; the pytest form of Django's assertNumQueries().
inline-snapshot-django 1.4.0 (2026-02-12) snapshot_queries() records the normalized SQL of a block and compares it with an inline-snapshot list stored in the test, which inline-snapshot writes and updates for you. By the author of django-perf-rec.
django-perf-rec 4.31.0 (2025-09-18) Records the queries and cache operations of a block to a YAML file next to the test and fails when they change.
django-assert-queries 3.0 (2026-11-11) assert_queries() compares each executed query with an expected list of its model, tables and where clause (as a Q object), and prints a diff of every query that does not match.
django-query-guard 0.2.1 (2026-08-07) A query_guard marker and context manager with max_queries and a repeated-normalized-query check (2 repeats by default), an HTML report and a JSON run history.
pytest-django-queries 1.3.0 (2026-03-01) Counts the queries of marked tests (count_queries) and builds a coverage-style report, with a command to diff two runs.
django-queryhunter 1.1.0 (2025-07-17) A context manager and middleware that report, for each line of application code, how many queries it ran and how long they took.
django-query-counter 0.7.0 (2026-10-02) A decorator and middleware that print the query count, the duplicated queries and the slowest ones to the console; for views, management commands and Celery tasks.

What pytest-queryguard does differently: it needs no marker, fixture or expected list, names the relationship behind an N+1 and suggests select_related() or prefetch_related(), and has a baseline, SARIF and the missing-index check. What it does not have: snapshots of the statements themselves (its budgets are counts, and assert_queries_do_not_grow() compares counts), cache operations, or assertions on the model and where clause of each query. If you want a test to pin the exact SQL a view runs, inline-snapshot-django or django-assert-queries do that and can run alongside pytest-queryguard.

pytest-capquery's PyPI metadata has no license field. Its README badge and the LICENSE file in its GitHub repository are Creative Commons Attribution-NonCommercial-ShareAlike 4.0, which is not an open-source license and restricts commercial use. Read it before you adopt it.

Feature matrix#

pytest-queryguard queryspy 0.6.0 pytest-querycount 0.4.0 nplusone 1.0.0 django-zeal 2.3.0 fastapi-nplusone 0.1.0 pytest-capquery 0.3.3
Works with SQLAlchemy 2 yes yes (v) yes (v) no: import fails on 2.1.4, silent or errors on 2.0.54 and 1.4.54 (v) not applicable (Django only) (r) SQLAlchemy, version not stated (r) SQLAlchemy, version not stated (r)
Fails tests with no marker or option yes (v) no: --queryspy-strict or queryspy_fail_on; budgets only with a marker or queryspy_budget (v) no: markers, or --querycount-max (v) not a pytest plugin (r) needs a fixture or middleware setup (r) logs a warning from a middleware (r) needs a fixture; assertions in the test (r)
N+1 from lazy-loaded relationships yes (v) yes (v) by repeated statement shape, without the relationship name (v) yes, SQLAlchemy 1.3.24 only (v) yes, Django (r) by repeated normalized query per request (r) by an expected query count in a block (r)
Repeated statements (session.get() loops, Core, text()) yes (v) session.get() loops yes; a Core select() loop and a loop with literal values not reported (v) yes (v) no (r) Django only yes (r) by count (r)
Deferred and expired column loads yes, with the right hint (v) yes, with the right hint (v) as a repeated statement, generic hint (v) no (r) .only() and .defer() (r) no (r) no (r)
Hint: joinedload or selectinload by cardinality yes (v) yes (v) generic text (v) no Django hints (r) no no
Query budget (max_queries) yes (v) yes (v) yes (v) no no no exact count in a block (r)
Budget failure lists every statement with its call site yes (v) no: the marker and queryspy_budget print only "expected at most N, got M"; the assert_max_queries() context manager adds the database time and N+1 findings, not the statements (v, 2026-10-13) yes, with timing (v) not applicable not applicable not applicable prints a copy-paste assertion (r)
Time budget and per-query timing max_db_time, timing in QueryLog (v) timing and the slowest statement; no time-budget option in the installed 0.5.0 (v, 2026-10-13) timing in the failure and the report (v) no no no no
Baseline for existing findings yes (v) yes (v) no baseline; --querycount-write-budgets writes exact budgets into your tests (v) no allow-list in settings (r) no no
SARIF and a GitHub Action SARIF yes; a composite action in this repository, action/ (v) SARIF yes (v: _serialize.py in the installed package); an action, sqla-native/queryspy@v0 (r) not found: no SARIF code in the installed package (v) no no no no
Missing-index check PostgreSQL 16+, SQLite, and MySQL and MariaDB (tested in CI on MySQL 8.4 and MariaDB 11.8), with a CREATE INDEX; hypopg verification on PostgreSQL (v) none: no EXPLAIN code in the installed package (v) PostgreSQL only, no_seq_scan, with a CREATE INDEX suggestion (v) no no no no
Unused eager loads experimental, off by default (v) no, deliberately (r) no yes, for Flask-SQLAlchemy and Django per its README (r) no (r) no no
Row-by-row write loops opt-in (v) not reported (v) not reported (v) no no no no
Per-finding ignore marker, ini patterns, baseline and an ignore() block (v) marker and an ignore() block (v) ignore= for the index check only (r) whitelist and an ignore block (r) allow-list and an ignore block; since 2.3.0 an opt-in check for unused zeal_ignore blocks (r) no no
In-app middleware and request panel yes, since 0.5.0: ASGI and WSGI, optional panel (v) yes: ASGI and WSGI, optional panel (v: modules present) no Django, Flask-SQLAlchemy, WSGI (r) Django middleware (r) yes, FastAPI middleware (r) no
Async SQLAlchemy yes (v) yes (v) yes (v) no no not stated yes, through sync_engine (r)
pytest-xdist tested in CI not stated summary per worker; budgets and N+1 unaffected (r) not stated not stated not stated not stated
Documentation site this site yes (r) README README README README README

"not stated" means I did not find a statement in the README, not that it does not work.

Where the others are ahead#

Common problems with other tools#

The issue trackers of N+1 tools, in Python and in Ruby (Bullet and Prosopite, for Rails), show problems that users run into again and again. Some of them pytest-queryguard was built to avoid; the list below names only those, with where the behaviour is documented. The linked issues are evidence that the problem exists, not a judgement of the projects, several of which have fixed or worked around them since.

A problem that pytest-queryguard shares: a test that hands every request one Session makes the requests one unit of work, and queryspy#14 is also about that. See A session per request in a test transaction.

What I measured#

Head-to-head in GitHub Actions#

Measured on 2026-11-10 by the head-to-head workflow (.github/workflows/head-to-head.yml, the adapters in scripts/head_to_head/), which anyone can run again from the Actions tab; it also runs once a month. Every tool that runs inside pytest and supports SQLAlchemy 2 is in it: queryspy 0.6.0, pytest-querycount 0.4.0, n-plus-one-sniffer (not on PyPI, installed from git at d4790f8, reported as 0.1.0) and nplusone 1.0.0. orm-lens is not: it reads source code and has no pytest mode. redline (found on 2026-11-14) is not either: its pytest marker checks requests sent through an instrumented test client, and all but six of the corpus scenarios send none. pytest-queryguard is 1.0.0rc1, run from its tag v1.0.0rc1; 1.0.0 has the same code. Python 3.13.18, SQLAlchemy 2.1.1, pytest 9.1.1 on ubuntu-latest (x86_64, 4 CPUs).

How each tool is run, in its own job: its defaults plus what its own documentation says makes a test fail on an N+1. queryspy with --queryspy-strict; pytest-querycount and n-plus-one-sniffer with their no_n_plus_one marker on every test (n-plus-one-sniffer also needs an nplusone_engine fixture, which returns the Engine class so it sees every engine a scenario creates); nplusone with its documented generic use, import nplusone.ext.sqlalchemy and a Profiler() around each test. A scenario counts as flagged when the tool's own exception or message is in the failed test's report (or, for pytest-queryguard, when it recorded a finding); a test that failed for any other reason is an error, never a pass. A run with no tool at all passes every scenario.

Accuracy, on the 278 scenarios of the accuracy corpus that ran (135 BUG, 143 CLEAN):

tool BUG flagged CLEAN flagged errors precision recall (all BUG) recall (BUG of kinds it claims)
pytest-queryguard, defaults 117 2 0 98% 87% 97%
pytest-queryguard, all opt-in rules 134 9 0 94% 99% 99%
queryspy 0.6.0 110 34 0 76% 81% 96%
pytest-querycount 0.4.0 115 35 0 77% 85% 100%
n-plus-one-sniffer d4790f8 115 30 0 79% 85% 97%
nplusone 1.0.0, SQLAlchemy 2.1.1 0 0 278 n/a 0% 0%
nplusone 1.0.0, SQLAlchemy 2.0.54 1 0 2 100% 1% 2%

Precision and recall per finding kind, with n/a for the kinds a tool does not claim (not 0%), and what each tool missed or flagged wrongly, are on the accuracy page and in the run's summary.

Read this table with its bias in mind: the corpus was written by the author of pytest-queryguard, for pytest-queryguard. Its CLEAN scenarios include the shapes pytest-queryguard was taught to leave alone (pagination, IN chunks, selectinload batches, yield_per), three of them use its own ignore() API, and the thresholds of the other tools were left at their defaults. What the table does show: the three working plugins catch nearly every N+1 shape they claim (pytest-querycount all of them), and each fails 30 to 35 of the 143 CLEAN scenarios, where pytest-queryguard fails 2 by default. nplusone does not import on SQLAlchemy 2.1, and on 2.0 it misses every lazy load of the corpus (2.0-style select() bypasses the Query.__iter__ it patches) and raises AttributeError on two subqueryload scenarios.

Overhead, same run (its overhead job ran twice: in the first attempt the run with no tool varied by 38% between rounds, so the numbers below are from the second), one job, every tool in its own virtual environment with the same Python, pytest and SQLAlchemy, the tools interleaved and their order reversed every round, 15 rounds, each a fresh process pinned to one core. Per statement: scripts/compare/bench_micro.py (in-memory SQLite), the best round. The suite: the generated 300-test suite of scripts/bench_suite.py against file SQLite, each tool set to look for N+1 in every test (pytest-querycount at threshold=3: its default of 2 fails the suite, which reads one parent twice per test).

pytest-queryguard queryspy pytest-querycount n-plus-one-sniffer
300-test suite, added wall time (best of 15) +14.8% +25.8% +16.3% +23.0%
300-test suite, added wall time (median of 15) +13.1% +25.7% +15.6% +22.9%
Core select, added per statement +18.9 us +8.4 us +68.5 us +14.0 us
ORM select, added per statement +33.5 us +105.4 us +107.6 us +13.6 us
Lazy load, added per statement +66.0 us +139.1 us +121.3 us +24.3 us

n-plus-one-sniffer adds the least to an ORM statement and a lazy load (one before_cursor_execute listener and a regular expression) but about 23% to the suite, so most of its cost is outside the statements measured here; queryspy adds the least to a Core statement. pytest-queryguard adds the least to the suite, with pytest-querycount close behind.

The run of 2026-11-07 gave pytest-queryguard 0.8.0 +0.8% (best) and +1.7% (median) on the same suite. I could not reproduce it: the first attempt of this run gave +0.7% for the median too, but from a runner whose times varied by 38%, and on my laptop on 2026-11-10 (scripts/bench_suite.py --runs 5, CPU time of the test process) 0.8.0, 0.9.0, 0.10.0 and 1.0.0rc1 each added 18 to 20% to this suite. Read the suite cost as about a seventh to a fifth of the run time of a suite this cheap (about 5 ms a test), the same since 0.8.0, not 2%. nplusone has no overhead figure: it does not import on SQLAlchemy 2.1. Shared CI runners are noisy, which is why both the best and the median are given.

N+1 and budgets on SQLite#

The head-to-head above runs the scenarios of the accuracy page under every tool (252 on the day it ran; the page now has 274, with precision and recall per finding kind). The smaller table below is the first comparison, of 2026-10-12.

I ran 45 scenarios in tests/scenarios (SQLAlchemy ORM and Core, sync and async, SQLite) against three packages, each in its own virtual environment on 2026-10-12: pytest-queryguard next at b64d19c, queryspy 0.5.0 and pytest-querycount 0.4.0, with Python 3.13, SQLAlchemy 2.1.4 and pytest 9.1.1. The first 41 scenarios are the ones from an earlier comparison; the four scenarios 09d, 09e, 11d and 11e were added later for pytest-queryguard's own tests.

How each tool was run: pytest-queryguard with its defaults; queryspy with --queryspy-strict (without it, only the budgets in the scenarios fail: 2 of 45 tests); pytest-querycount with @pytest.mark.no_n_plus_one on every test that has no budget (without markers, all 45 pass). Budgets use the tool's own marker. The "queryguard, small-repeat and write-loop on" column adds queryguard_small_repeat_threshold = 2 and queryguard_write_loop_threshold = 2.

"Right verdict" is my judgement from the scenario's name (_bad should fail, _ok and _legit should pass); scenarios where I could not say are marked -. The scenarios were written for pytest-queryguard, and some of them test decisions it made on purpose (for example, three session.get() calls are below its default threshold), so the table is biased towards the tool that wrote it.

Scenario Right verdict queryguard queryguard, small-repeat and write-loop on queryspy pytest-querycount
01_lazy_n1_bad fail FAIL FAIL FAIL FAIL
02a_selectinload_ok pass pass pass pass pass
02b_joinedload_ok pass pass pass pass pass
02c_subqueryload_ok pass pass pass pass pass
03_session_get_loop_bad fail FAIL FAIL FAIL FAIL
03b_session_get_loop_3_bad fail pass (wrong) FAIL FAIL FAIL
04_async_awaitable_attrs_bad fail FAIL FAIL FAIL FAIL
04b_async_selectin_ok pass pass pass pass pass
04c_async_get_loop_bad fail FAIL FAIL FAIL FAIL
05a_repeat_x2 - pass FAIL FAIL FAIL
05b_repeat_x3_batch_legit - pass FAIL FAIL FAIL
05c_repeat_x4 - pass FAIL FAIL FAIL
05d_repeat_x5 - FAIL FAIL FAIL FAIL
05e_repeat_x6 - FAIL FAIL FAIL FAIL
06_legit_diff_shapes_ok pass pass pass pass pass
07a_budget_exact_ok pass pass pass pass pass
07b_budget_over_by_1_bad fail FAIL FAIL FAIL FAIL
08_m2m_lazy_bad fail FAIL FAIL FAIL FAIL
08b_m2m_selectin_ok pass pass pass pass pass
09_selfref_parent_walk_bad fail pass (wrong) pass (wrong) pass (wrong) pass (wrong)
09b_selfref_joined_ok pass pass pass pass pass
09c_selfref_kids_lazy_bad fail FAIL FAIL FAIL FAIL
09d_many_to_one_lazy_bad fail FAIL FAIL FAIL FAIL
09e_many_to_one_joinedload_ok pass pass pass pass pass
10a_dynamic_loop_bad fail FAIL FAIL FAIL FAIL
10b_writeonly_loop_bad fail FAIL FAIL FAIL FAIL
10c_raiseload_ok pass pass pass pass pass
11a_deferred_loop_bad fail FAIL FAIL FAIL FAIL
11b_undefer_ok pass pass pass pass pass
11c_expire_after_commit_refresh_bad fail FAIL FAIL FAIL FAIL
11d_expire_after_commit_few_ok pass pass pass FAIL (wrong) FAIL (wrong)
11e_expire_on_commit_false_ok pass pass pass pass pass
12a_insert_flush_per_row - pass FAIL pass pass
12b_add_all_one_flush_ok pass pass pass pass pass
12c_core_insert_per_row - pass FAIL pass pass
12d_core_executemany_ok pass pass pass pass pass
12e_budget_counts_writes_bad fail FAIL FAIL FAIL FAIL
13a_core_select_loop_bad fail FAIL FAIL pass (wrong) FAIL
13b_count_loop_bad fail FAIL FAIL FAIL FAIL
14a_pagination_3_pages_legit pass pass pass FAIL (wrong) FAIL (wrong)
14b_two_parents_legit pass FAIL (wrong) FAIL (wrong) FAIL (wrong) FAIL (wrong)
14c_same_parent_twice_ok pass pass pass pass pass
14d_identity_map_get_ok pass pass pass pass pass
14e_in_list_varying_len_legit pass FAIL (wrong) FAIL (wrong) FAIL (wrong) FAIL (wrong)
14f_literal_binds_loop_bad fail FAIL FAIL pass (wrong) FAIL

Score, on the 38 scenarios with a right verdict: pytest-queryguard 34, with the two extra rules on 35, queryspy 31, pytest-querycount 33. On the 34 of those that belong to the original 41: 30, 31, 28 and 30. These numbers measure agreement with my labels, not how useful a tool is. What the table shows:

Missing indexes on PostgreSQL#

14 scenarios on PostgreSQL 17.11 (docker, the official image), with pytest-queryguard --queryguard-index-check through two drivers and pytest-querycount --querycount-no-seq-scan. queryspy has no such check, so it is not in the table. The tables have 20 to 40 rows. Python 3.13, SQLAlchemy 2.1.4. The advisor ran without hypopg.

Scenario Right verdict queryguard (pg8000) queryguard (psycopg 3) pytest-querycount (psycopg 3)
i01: equality on an unindexed FK column fail FAIL FAIL FAIL
i02: equality on an indexed column pass pass pass pass
i03: SELECT without a filter pass pass pass pass
i04: primary-key lookup pass pass pass pass
i05: lower(email) with an expression index pass pass pass pass
i06: lower(city) with no expression index fail FAIL FAIL FAIL
i07: filter on the second column of a two-column index fail FAIL FAIL pass (wrong)
i08: filter on the first column of that index pass pass pass pass
i09: LIKE prefix on an unindexed text column fail FAIL FAIL FAIL
i10: ORDER BY id LIMIT 5, no filter pass pass pass pass
i11: range on an unindexed timestamp fail FAIL FAIL FAIL
i12: filter on a 2-row lookup table, no index - FAIL FAIL FAIL
i13: join on an unindexed FK, no WHERE pass pass pass pass
i14: IN list on an unindexed FK column fail FAIL FAIL FAIL

i07 is a judgement call: the two-column index can serve the filter with a full index scan, and PostgreSQL 18 may skip-scan it. pytest-queryguard reports it on PostgreSQL 16 and 17 and pytest-querycount does not. On the 13 scenarios with a right verdict, pytest-queryguard agreed with my labels on 13 with both drivers, pytest-querycount on 12. Both report the 2-row lookup table (i12), which is by design; both give you a way to exclude such tables. pytest-queryguard's finding also includes an Alembic call for simple cases and says "an expression index may be needed" for i06; pytest-querycount's suggests CREATE INDEX for plain columns and gives no suggestion for the expression.

Overhead#

See the head-to-head above for the numbers of 2026-11-10 on a CI runner. The earlier measurement of 2026-11-05 on my machine (pytest-queryguard 0.5.0, pytest-querycount 0.4.0, queryspy 0.6.0), with its method and the script scripts/compare/run.py, is in Performance: +1.8 to +2.4% for pytest-queryguard on the same suite, +27 to +29% for pytest-querycount and +40 to +43% for queryspy.

What I did not measure#

SQLite for the index check (the page for it has its own tests), MySQL, PostgreSQL versions other than 17, async drivers in this comparison, memory, other SQLAlchemy versions, and any real application. Speed was measured on one machine, above; the overhead gate in scripts/bench_overhead.py covers pytest-queryguard only.

Choosing#

Edit this page on GitHub