summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorMy-Name-Is-Nabil <midorady9999@gmail.com>2022-01-15 01:38:31 +0200
committerMariusz Felisiak <felisiak.mariusz@gmail.com>2022-01-17 09:00:46 +0100
commitf37face331f21cb8af70fc4ec101ec7b6be1f63e (patch)
treeed1beb96fa8cfbf050aa7294838d2311255d4b43
parentb55ebe32417e0884b6b8b3e1bc0379033aa221af (diff)
Fixed #33435 -- Fixed invalid SQL generatered by Subquery.as_sql().
-rw-r--r--django/db/models/expressions.py3
-rw-r--r--tests/expressions/tests.py9
2 files changed, 11 insertions, 1 deletions
diff --git a/django/db/models/expressions.py b/django/db/models/expressions.py
index 6f26dff0e0..81f8f79c71 100644
--- a/django/db/models/expressions.py
+++ b/django/db/models/expressions.py
@@ -1149,7 +1149,8 @@ class Subquery(BaseExpression, Combinable):
def __init__(self, queryset, output_field=None, **extra):
# Allow the usage of both QuerySet and sql.Query objects.
- self.query = getattr(queryset, 'query', queryset)
+ self.query = getattr(queryset, 'query', queryset).clone()
+ self.query.subquery = True
self.extra = extra
super().__init__(output_field)
diff --git a/tests/expressions/tests.py b/tests/expressions/tests.py
index 06c9ad597a..5cf9dd1ea5 100644
--- a/tests/expressions/tests.py
+++ b/tests/expressions/tests.py
@@ -537,6 +537,15 @@ class BasicExpressionsTests(TestCase):
qs.query.annotations['small_company'],
)
+ def test_subquery_sql(self):
+ employees = Employee.objects.all()
+ employees_subquery = Subquery(employees)
+ self.assertIs(employees_subquery.query.subquery, True)
+ self.assertIs(employees.query.subquery, False)
+ compiler = employees_subquery.query.get_compiler(connection=connection)
+ sql, _ = employees_subquery.as_sql(compiler, connection)
+ self.assertIn('(SELECT ', sql)
+
def test_in_subquery(self):
# This is a contrived test (and you really wouldn't write this query),
# but it is a succinct way to test the __in=Subquery() construct.