Detecting and preventing N+1 queries with a query-count test

Django N+1 Queries November 13, 2026 python

How do you detect and prevent N+1 queries?

python
1
2
3
4
5
6
7
8
# ======================================================================
# Q: How do you detect and prevent N+1 queries?
# ======================================================================

def test_order_list_queries(api_client, django_assert_num_queries):
    OrderFactory.create_batch(20, items=3)
    with django_assert_num_queries(3):   # auth + orders + items
        api_client.get('/api/orders/')