1
0
mirror of https://github.com/django/django.git synced 2025-10-31 01:25:32 +00:00

Refs #28586 -- Copied fetch modes to related objects.

This change ensures that behavior and performance remain consistent when
traversing relationships.
This commit is contained in:
Adam Johnson
2025-04-14 15:12:28 +01:00
committed by Jacob Walls
parent 821619aa87
commit 6dc9b04018
12 changed files with 310 additions and 14 deletions

View File

@@ -3,7 +3,13 @@ from unittest import mock
from django.contrib.contenttypes.models import ContentType
from django.core.exceptions import ObjectDoesNotExist
from django.db import NotSupportedError, connection
from django.db.models import F, Prefetch, QuerySet, prefetch_related_objects
from django.db.models import (
FETCH_PEERS,
F,
Prefetch,
QuerySet,
prefetch_related_objects,
)
from django.db.models.fetch_modes import RAISE
from django.db.models.query import get_prefetcher
from django.db.models.sql import Query
@@ -108,6 +114,28 @@ class PrefetchRelatedTests(TestDataMixin, TestCase):
normal_books = [a.first_book for a in Author.objects.all()]
self.assertEqual(books, normal_books)
def test_fetch_mode_copied_fetching_one(self):
author = (
Author.objects.fetch_mode(FETCH_PEERS)
.prefetch_related("first_book")
.get(pk=self.author1.pk)
)
self.assertEqual(author._state.fetch_mode, FETCH_PEERS)
self.assertEqual(
author.first_book._state.fetch_mode,
FETCH_PEERS,
)
def test_fetch_mode_copied_fetching_many(self):
authors = list(
Author.objects.fetch_mode(FETCH_PEERS).prefetch_related("first_book")
)
self.assertEqual(authors[0]._state.fetch_mode, FETCH_PEERS)
self.assertEqual(
authors[0].first_book._state.fetch_mode,
FETCH_PEERS,
)
def test_fetch_mode_raise(self):
authors = list(Author.objects.fetch_mode(RAISE).prefetch_related("first_book"))
authors[0].first_book # No exception, already loaded