1
0
mirror of https://github.com/django/django.git synced 2025-11-07 07:15:35 +00:00

Fixed #28586 -- Added model field fetch modes.

May your database queries be much reduced with minimal effort.

co-authored-by: Andreas Pelme <andreas@pelme.se>
co-authored-by: Simon Charette <charette.s@gmail.com>
co-authored-by: Jacob Walls <jacobtylerwalls@gmail.com>
This commit is contained in:
Adam Johnson
2023-11-29 09:35:34 +00:00
committed by Jacob Walls
parent f6bd90c840
commit e097e8a12f
24 changed files with 682 additions and 73 deletions

View File

@@ -26,6 +26,51 @@ only officially support, the latest release of each series.
What's new in Django 6.1
========================
Model field fetch modes
-----------------------
The on-demand fetching behavior of model fields is now configurable with
:doc:`fetch modes </topics/db/fetch-modes>`. These modes allow you to control
how Django fetches data from the database when an unfetched field is accessed.
Django provides three fetch modes:
1. ``FETCH_ONE``, the default, fetches the missing field for the current
instance only. This mode represents Django's existing behavior.
2. ``FETCH_PEERS`` fetches a missing field for all instances that came from
the same :class:`~django.db.models.query.QuerySet`.
This mode works like an on-demand ``prefetch_related()``. It can reduce most
cases of the "N+1 queries problem" to two queries without any work to
maintain a list of fields to prefetch.
3. ``RAISE`` raises a :exc:`~django.core.exceptions.FieldFetchBlocked`
exception.
This mode can prevent unintentional queries in performance-critical
sections of code.
Use the new method :meth:`.QuerySet.fetch_mode` to set the fetch mode for model
instances fetched by the ``QuerySet``:
.. code-block:: python
from django.db import models
books = Book.objects.fetch_mode(models.FETCH_PEERS)
for book in books:
print(book.author.name)
Despite the loop accessing the ``author`` foreign key on each instance, the
``FETCH_PEERS`` fetch mode will make the above example perform only two
queries:
1. Fetch all books.
2. Fetch associated authors.
See :doc:`fetch modes </topics/db/fetch-modes>` for more details.
Minor features
--------------