diff --git a/django/db/models/expressions.py b/django/db/models/expressions.py index 93fc7df82b..b5090d6771 100644 --- a/django/db/models/expressions.py +++ b/django/db/models/expressions.py @@ -818,6 +818,8 @@ class When(Expression): condition, lookups = Q(**lookups), None if condition is None or not getattr(condition, 'conditional', False) or lookups: raise TypeError("__init__() takes either a Q object or lookups as keyword arguments") + if isinstance(condition, Q) and not condition: + raise ValueError("An empty Q() can't be used as a When() condition.") super().__init__(output_field=None) self.condition = condition self.result = self._parse_expressions(then)[0] diff --git a/tests/expressions_case/tests.py b/tests/expressions_case/tests.py index 69e299bde9..90aba36031 100644 --- a/tests/expressions_case/tests.py +++ b/tests/expressions_case/tests.py @@ -1301,3 +1301,8 @@ class CaseWhenTests(SimpleTestCase): When(condition=object()) with self.assertRaisesMessage(TypeError, msg): When() + + def test_empty_q_object(self): + msg = "An empty Q() can't be used as a When() condition." + with self.assertRaisesMessage(ValueError, msg): + When(Q(), then=Value(True))