diff --git a/django/db/migrations/state.py b/django/db/migrations/state.py index 42a2c80a5e..e13de5ba6f 100644 --- a/django/db/migrations/state.py +++ b/django/db/migrations/state.py @@ -761,8 +761,11 @@ class ModelState: return self.name.lower() def get_field(self, field_name): - if field_name == "_order": - field_name = self.options.get("order_with_respect_to", field_name) + if ( + field_name == "_order" + and self.options.get("order_with_respect_to") is not None + ): + field_name = self.options["order_with_respect_to"] return self.fields[field_name] @classmethod diff --git a/tests/migrations/test_state.py b/tests/migrations/test_state.py index c64e4ebb4d..dbbdf77734 100644 --- a/tests/migrations/test_state.py +++ b/tests/migrations/test_state.py @@ -1131,6 +1131,22 @@ class StateTests(SimpleTestCase): self.assertIsNone(order_field.related_model) self.assertIsInstance(order_field, models.PositiveSmallIntegerField) + def test_get_order_field_after_removed_order_with_respect_to_field(self): + new_apps = Apps() + + class HistoricalRecord(models.Model): + _order = models.PositiveSmallIntegerField() + + class Meta: + app_label = "migrations" + apps = new_apps + + model_state = ModelState.from_model(HistoricalRecord) + model_state.options["order_with_respect_to"] = None + order_field = model_state.get_field("_order") + self.assertIsNone(order_field.related_model) + self.assertIsInstance(order_field, models.PositiveSmallIntegerField) + def test_manager_refer_correct_model_version(self): """ #24147 - Managers refer to the correct version of a