Django 6.1's FETCH_PEERS collapses a 2,001-query loop into 2
A loop over 2,000 Django model instances that touched a foreign key on each one fired 2,001 queries against Postgres and took, at its fastest run, 1.14 seconds on localhost. That is the N+1 problem everyone who has used Django has hit at least once. Django 6.1, released on 5 August 2026, added a way to fix it without adding select_related() or prefetch_related() calls at every call site: a…
Django 6.1 introduced a new feature called fetch_mode, which can dramatically improve performance when dealing with N+1 query problems in Django applications. In a test setup with 50 authors and 2,000 books, a loop over all books that fetched the author's name resulted in 2,001 queries and took 1.14 seconds to complete. By switching to use fetch_mode(FETCH_PEERS), the number of queries was reduced to just 2, cutting the wall time down to 13.1ms, an 87x improvement.
The technique worked equally well with deferred fields and even when loading only specific fields. However, it has limitations - it doesn't affect reverse foreign key managers, and setting it on a parent queryset doesn't help with the related child queryset. Additionally, it has a mode called FETCH_RAISE that can catch accidental lazy loading.
Written by urgent.news from Dev.to's reporting — not their text. Machine-written — may contain errors; check the original before relying on it.