diff --git a/django/db/models/query.py b/django/db/models/query.py index a21a091af0..1544beb613 100644 --- a/django/db/models/query.py +++ b/django/db/models/query.py @@ -1556,7 +1556,7 @@ def prefetch_related_objects(model_instances, *related_lookups): while all_lookups: lookup = all_lookups.pop() if lookup.prefetch_to in done_queries: - if lookup.queryset: + if lookup.queryset is not None: raise ValueError("'%s' lookup was already seen with a different queryset. " "You may need to adjust the ordering of your lookups." % lookup.prefetch_to) diff --git a/tests/prefetch_related/tests.py b/tests/prefetch_related/tests.py index 0b3caed0dc..49c7fd8ff6 100644 --- a/tests/prefetch_related/tests.py +++ b/tests/prefetch_related/tests.py @@ -400,11 +400,16 @@ class CustomPrefetchTests(TestCase): "'houses' lookup was already seen with a different queryset. You " "may need to adjust the ordering of your lookups." ) - with self.assertRaisesMessage(ValueError, msg): - self.traverse_qs( - Person.objects.prefetch_related('houses__rooms', Prefetch('houses', queryset=House.objects.all())), - [['houses', 'rooms']] - ) + # lookup.queryset shouldn't be evaluated. + with self.assertNumQueries(3): + with self.assertRaisesMessage(ValueError, msg): + self.traverse_qs( + Person.objects.prefetch_related( + 'houses__rooms', + Prefetch('houses', queryset=House.objects.all()), + ), + [['houses', 'rooms']], + ) # Ambiguous: Lookup houses_lst doesn't yet exist when performing houses_lst__rooms. msg = (