Django 6.1's FETCH_PEERS cuts N+1 query loops from 2,001 queries to just 2
Django 6.1, released on 5 August 2026, introduced a queryset-level setting called fetch_mode with a FETCH_PEERS option designed to automatically batch foreign key lookups without requiring explicit select_related() or prefetch_related() calls. In benchmark tests using 2,000 book records across 50 authors on a local Postgres 17 instance, the default N+1 approach fired 2,001 queries and took 1,144.6 ms, while FETCH_PEERS reduced that to just 2 queries and 13.1 ms — nearly matching select_related performance. The feature works by issuing a single WHERE id IN (...) batch query on first access, functioning like an on-demand prefetch_related(), and also handles deferred fields beyond just foreign keys. However, testing revealed a documented limitation: FETCH_PEERS does not apply to reverse foreign key managers, meaning a loop over author.books.all() still produces the same number of queries regardless of the fetch_mode setting on the parent queryset.
This is an AI-generated summary. ShortSingh links to the original source for the complete article.


Discussion (0)
Log in to join the discussion and vote.
Log in