From 25157033e979c134d455d46995a6db0838457d98 Mon Sep 17 00:00:00 2001
From: Hannes Ljungberg <hannes.ljungberg@gmail.com>
Date: Wed, 3 Nov 2021 13:28:04 +0100
Subject: [PATCH] Fixed #33260 -- Fixed crash when chaining QuerySet.exists()
 after select_for_update(of=()).

---
 django/db/models/sql/compiler.py | 2 ++
 tests/select_for_update/tests.py | 8 ++++++++
 2 files changed, 10 insertions(+)

diff --git a/django/db/models/sql/compiler.py b/django/db/models/sql/compiler.py
index d1009847e7..32657a3e40 100644
--- a/django/db/models/sql/compiler.py
+++ b/django/db/models/sql/compiler.py
@@ -1077,6 +1077,8 @@ class SQLCompiler:
                     (path, klass_info)
                     for klass_info in klass_info.get('related_klass_infos', [])
                 )
+        if not self.klass_info:
+            return []
         result = []
         invalid_names = []
         for name in self.query.select_for_update_of:
diff --git a/tests/select_for_update/tests.py b/tests/select_for_update/tests.py
index 705975b760..5bae8a355a 100644
--- a/tests/select_for_update/tests.py
+++ b/tests/select_for_update/tests.py
@@ -244,6 +244,14 @@ class SelectForUpdateTests(TransactionTestCase):
             values = list(Person.objects.select_related('born').select_for_update(of=('self',)).values('born__name'))
         self.assertEqual(values, [{'born__name': self.city1.name}])
 
+    @skipUnlessDBFeature(
+        'has_select_for_update_of', 'supports_select_for_update_with_limit',
+    )
+    def test_for_update_of_with_exists(self):
+        with transaction.atomic():
+            qs = Person.objects.select_for_update(of=('self', 'born'))
+            self.assertIs(qs.exists(), True)
+
     @skipUnlessDBFeature('has_select_for_update_nowait')
     def test_nowait_raises_error_on_block(self):
         """