1
0
mirror of https://github.com/django/django.git synced 2025-10-24 06:06:09 +00:00

Fixed #33651 -- Added support for prefetching GenericForeignKey.

Co-authored-by: revanthgss <revanthgss@almabase.com>
Co-authored-by: Mariusz Felisiak <felisiak.mariusz@gmail.com>
This commit is contained in:
Clément Escolano
2023-08-01 23:31:40 +02:00
committed by Mariusz Felisiak
parent 190874eadd
commit cac94dd8aa
15 changed files with 473 additions and 42 deletions

View File

@@ -1,6 +1,7 @@
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes.prefetch import GenericPrefetch
from django.core.exceptions import FieldError
from django.db.models import Q
from django.db.models import Q, prefetch_related_objects
from django.test import SimpleTestCase, TestCase, skipUnlessDBFeature
from .models import (
@@ -747,6 +748,38 @@ class GenericRelationsTests(TestCase):
comparison.first_obj.comparisons.all(), [comparison]
)
def test_generic_prefetch(self):
tagged_vegetable = TaggedItem.objects.create(
tag="great", content_object=self.bacon
)
tagged_animal = TaggedItem.objects.create(
tag="awesome", content_object=self.platypus
)
# Getting the instances again so that content object is deferred.
tagged_vegetable = TaggedItem.objects.get(pk=tagged_vegetable.pk)
tagged_animal = TaggedItem.objects.get(pk=tagged_animal.pk)
with self.assertNumQueries(2):
prefetch_related_objects(
[tagged_vegetable, tagged_animal],
GenericPrefetch(
"content_object",
[Vegetable.objects.all(), Animal.objects.only("common_name")],
),
)
with self.assertNumQueries(0):
self.assertEqual(tagged_vegetable.content_object.name, self.bacon.name)
with self.assertNumQueries(0):
self.assertEqual(
tagged_animal.content_object.common_name,
self.platypus.common_name,
)
with self.assertNumQueries(1):
self.assertEqual(
tagged_animal.content_object.latin_name,
self.platypus.latin_name,
)
class ProxyRelatedModelTest(TestCase):
def test_default_behavior(self):