django/django/db/models/fetch_modes.py
Adam Johnson e097e8a12f 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>
2025-10-16 14:52:22 -04:00

52 lines
1.1 KiB
Python

from django.core.exceptions import FieldFetchBlocked
class FetchMode:
__slots__ = ()
track_peers = False
def fetch(self, fetcher, instance):
raise NotImplementedError("Subclasses must implement this method.")
class FetchOne(FetchMode):
__slots__ = ()
def fetch(self, fetcher, instance):
fetcher.fetch_one(instance)
FETCH_ONE = FetchOne()
class FetchPeers(FetchMode):
__slots__ = ()
track_peers = True
def fetch(self, fetcher, instance):
instances = [
peer
for peer_weakref in instance._state.peers
if (peer := peer_weakref()) is not None
]
if len(instances) > 1:
fetcher.fetch_many(instances)
else:
fetcher.fetch_one(instance)
FETCH_PEERS = FetchPeers()
class Raise(FetchMode):
__slots__ = ()
def fetch(self, fetcher, instance):
klass = instance.__class__.__qualname__
field_name = fetcher.field.name
raise FieldFetchBlocked(f"Fetching of {klass}.{field_name} blocked.") from None
RAISE = Raise()