Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fixed #23266 -- Prevented extra query when checking for object types in query relation lookups in case of QuerySet. #3039

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
15 changes: 13 additions & 2 deletions django/db/models/sql/query.py
Expand Up @@ -1101,11 +1101,22 @@ def check_related_objects(self, field, value, opts):
"""
Checks the type of object passed to query relations.
"""
from django.db.models.query import QuerySet

if field.rel:
# testing for iterable of models
if hasattr(value, '__iter__'):
for v in value:
self.check_query_object_type(v, opts)
if isinstance(value, QuerySet):
model = value.model
if not (model == opts.concrete_model
or opts.concrete_model in model._meta.get_parent_list()
or model in opts.get_parent_list()):
raise ValueError(
'Cannot use QuerySet for "%s": Use a QuerySet for "%s".' %
(model._meta.model_name, opts.object_name))
else:
for v in value:
self.check_query_object_type(v, opts)
else:
# expecting single model instance here
self.check_query_object_type(value, opts)
Expand Down
4 changes: 4 additions & 0 deletions tests/queries/tests.py
Expand Up @@ -3441,6 +3441,10 @@ def test_correct_lookup(self):
# parent objects
self.assertQuerysetEqual(ObjectC.objects.exclude(childobjecta=self.oa), out_c)

# test for refs. #23226
with self.assertNumQueries(0):
ObjectB.objects.filter(objecta__in=ObjectA.objects.all())


class Ticket14056Tests(TestCase):
def test_ticket_14056(self):
Expand Down