From 6f185a53a2a7acad0ad8383267942d554527688a Mon Sep 17 00:00:00 2001 From: Mariusz Felisiak Date: Mon, 7 Feb 2022 20:34:21 +0100 Subject: [PATCH] Refs #33482 -- Fixed QuerySet selecting and filtering againts negated Exists() with empty queryset. Regression in b7d1da5a62fe4141beff2bfea565f7ef0038c94c. --- django/db/models/expressions.py | 5 ++++- tests/expressions/tests.py | 8 ++++++++ 2 files changed, 12 insertions(+), 1 deletion(-) diff --git a/django/db/models/expressions.py b/django/db/models/expressions.py index c71970636c..f31ff4d3df 100644 --- a/django/db/models/expressions.py +++ b/django/db/models/expressions.py @@ -1221,7 +1221,10 @@ class Exists(Subquery): ) except EmptyResultSet: if self.negated: - return '', () + features = compiler.connection.features + if not features.supports_boolean_expr_in_select_clause: + return "1=1", () + return compiler.compile(Value(True)) raise if self.negated: sql = 'NOT {}'.format(sql) diff --git a/tests/expressions/tests.py b/tests/expressions/tests.py index dcde321c57..1aa0049cbe 100644 --- a/tests/expressions/tests.py +++ b/tests/expressions/tests.py @@ -1918,6 +1918,14 @@ class ExistsTests(TestCase): ) self.assertSequenceEqual(qs, [manager]) + def test_select_negated_empty_exists(self): + manager = Manager.objects.create() + qs = Manager.objects.annotate( + not_exists=~Exists(Manager.objects.none()) + ).filter(pk=manager.pk) + self.assertSequenceEqual(qs, [manager]) + self.assertIs(qs.get().not_exists, True) + class FieldTransformTests(TestCase):