From 84206607d6bfd61e7f7a88b51163ffd4153e3b5a Mon Sep 17 00:00:00 2001
From: Sarah Boyce <42296566+sarahboyce@users.noreply.github.com>
Date: Mon, 10 Oct 2022 08:57:52 +0200
Subject: [PATCH] Fixed #32833 -- Fixed ContentTypeManager.get_for_models()
 crash when using in migrations.

Co-authored-by: Heraldo Lucena <23155511+HMaker@users.noreply.github.com>
---
 django/contrib/contenttypes/models.py   |  4 +++-
 tests/contenttypes_tests/test_models.py | 10 ++++++++++
 2 files changed, 13 insertions(+), 1 deletion(-)

diff --git a/django/contrib/contenttypes/models.py b/django/contrib/contenttypes/models.py
index 0c1c6400721..759a53ce674 100644
--- a/django/contrib/contenttypes/models.py
+++ b/django/contrib/contenttypes/models.py
@@ -89,7 +89,9 @@ class ContentTypeManager(models.Manager):
             )
             cts = self.filter(condition)
             for ct in cts:
-                opts_models = needed_opts.pop(ct.model_class()._meta, [])
+                opts_models = needed_opts.pop(
+                    ct._meta.apps.get_model(ct.app_label, ct.model)._meta, []
+                )
                 for model in opts_models:
                     results[model] = ct
                 self._add_to_cache(self.db, ct)
diff --git a/tests/contenttypes_tests/test_models.py b/tests/contenttypes_tests/test_models.py
index 2741556df73..d0aa08dd223 100644
--- a/tests/contenttypes_tests/test_models.py
+++ b/tests/contenttypes_tests/test_models.py
@@ -1,5 +1,7 @@
+from django.apps import apps
 from django.contrib.contenttypes.models import ContentType, ContentTypeManager
 from django.db import models
+from django.db.migrations.state import ProjectState
 from django.test import TestCase, override_settings
 from django.test.utils import isolate_apps
 
@@ -90,6 +92,14 @@ class ContentTypesTests(TestCase):
             },
         )
 
+    def test_get_for_models_migrations(self):
+        state = ProjectState.from_apps(apps.get_app_config("contenttypes"))
+        ContentType = state.apps.get_model("contenttypes", "ContentType")
+        cts = ContentType.objects.get_for_models(ContentType)
+        self.assertEqual(
+            cts, {ContentType: ContentType.objects.get_for_model(ContentType)}
+        )
+
     def test_get_for_models_full_cache(self):
         # Full cache
         ContentType.objects.get_for_model(ContentType)