From 5778b5701d6a0feb3053b70891cd8ce80b6e8601 Mon Sep 17 00:00:00 2001
From: Tim Martin <tim@asymptotic.co.uk>
Date: Sun, 5 Nov 2017 21:34:02 +0000
Subject: [PATCH] Fixed #28731 -- Added an error message when using an empty
 Q() in a When expression.

Otherwise it generates invalid SQL.
---
 django/db/models/expressions.py | 2 ++
 tests/expressions_case/tests.py | 5 +++++
 2 files changed, 7 insertions(+)

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))