Djangocon EU: auto-prefetching with model field fetch modes in Django 6.1 - Jacob Walls¶
(One of my summaries of the 2026 Djangocon EU in Athens).
There’s an example to experiment with here: https://dryorm.xterm.info/fetch-modes-simple
Timeline: it will be included in Django 6.1 in August.
The reason is the 1+n problem:
books = Book.objects.all()
for book in books:
print(book.author.name)
# This does a fresh query for author every time.
You can solve it with select_related(relation_names) or
prefetch_related(relation_names). The first does an inner join. The second does two
queries.
But: you might miss a relation. You might specify too many relations, getting data you don’t need. Or you might not know about the relation as the code is in a totally different part of the code.
Fetch mode is intended to solve it. You can append .fetch_mode(models.FETCH_xyz)
to your query:
models.FETCH_ONE: the current behaviour, which will be the default.models.FETCH_PEERS: Fetch a deferred field for all instances that came from the same queryset. More or lessprefetch_relatedin an automatic, lazy manner.models.FETCH_RAISE: useful for development, it will raiseFieldFetchBlocked. And it will thus tell you that you’ll have a performance problem and that you might need FETCH_PEERS
This is what happens:
books = Book.objects.all().fetch_mode(models.FETCH_PEERS)
for book in books:
# We're iterating over the query, so the query executes and grabs all books.
print(book.author.name)
# We accessed a relation, so at this point the prefetch_related-like
# mechanism ist fired off and all authors linked to by the books are
# grabbed in one single query.
You can write your own fetch modes, for instance if you only want a warning instead of raising an error.
Unrelated photo explanation: a cat I encountered in Athens on an evening stroll in the neighbourhood behind the hotel.