Skip to content

Commit

Permalink
Refs #33482 -- Fixed QuerySet selecting and filtering againts Exists(…
Browse files Browse the repository at this point in the history
…) with empty queryset.

Thanks Tobias Bengfort for the report.
  • Loading branch information
charettes authored Oct 4, 2023
1 parent 0989cf1 commit ea596a5
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 0 deletions.
9 changes: 9 additions & 0 deletions django/db/models/expressions.py
Original file line number Diff line number Diff line change
Expand Up @@ -1624,6 +1624,15 @@ def select_format(self, compiler, sql, params):
sql = "CASE WHEN {} THEN 1 ELSE 0 END".format(sql)
return sql, params

def as_sql(self, compiler, *args, **kwargs):
try:
return super().as_sql(compiler, *args, **kwargs)
except EmptyResultSet:
features = compiler.connection.features
if not features.supports_boolean_expr_in_select_clause:
return "1=0", ()
return compiler.compile(Value(False))


@deconstructible(path="django.db.models.OrderBy")
class OrderBy(Expression):
Expand Down
8 changes: 8 additions & 0 deletions tests/expressions/tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -2294,6 +2294,14 @@ def test_select_negated_empty_exists(self):
self.assertSequenceEqual(qs, [manager])
self.assertIs(qs.get().not_exists, True)

def test_filter_by_empty_exists(self):
manager = Manager.objects.create()
qs = Manager.objects.annotate(exists=Exists(Manager.objects.none())).filter(
pk=manager.pk, exists=False
)
self.assertSequenceEqual(qs, [manager])
self.assertIs(qs.get().exists, False)


class FieldTransformTests(TestCase):
@classmethod
Expand Down

0 comments on commit ea596a5

Please sign in to comment.