diff --git a/django/db/models/base.py b/django/db/models/base.py index 34e0d659803..dc59143eb57 100644 --- a/django/db/models/base.py +++ b/django/db/models/base.py @@ -296,12 +296,6 @@ class ModelBase(type): # Copy indexes so that index names are unique when models extend an # abstract model. new_class._meta.indexes = [copy.deepcopy(idx) for idx in new_class._meta.indexes] - # Set the name of _meta.indexes. This can't be done in - # Options.contribute_to_class() because fields haven't been added to - # the model at that point. - for index in new_class._meta.indexes: - if not index.name: - index.set_name_with_model(new_class) if abstract: # Abstract base models can't be instantiated and don't appear in @@ -359,6 +353,13 @@ class ModelBase(type): manager.auto_created = True cls.add_to_class('objects', manager) + # Set the name of _meta.indexes. This can't be done in + # Options.contribute_to_class() because fields haven't been added to + # the model at that point. + for index in cls._meta.indexes: + if not index.name: + index.set_name_with_model(cls) + class_prepared.send(sender=cls) @property diff --git a/docs/releases/1.11.6.txt b/docs/releases/1.11.6.txt index cc8e1bfa59b..ff9d4385fea 100644 --- a/docs/releases/1.11.6.txt +++ b/docs/releases/1.11.6.txt @@ -11,3 +11,6 @@ Bugfixes * Made the ``CharField`` form field convert whitespace-only values to the ``empty_value`` when ``strip`` is enabled (:ticket:`28555`). + +* Fixed crash when using the name of a model's autogenerated primary key + (``id``) in an ``Index``'s ``fields`` (:ticket:`28597`). diff --git a/tests/model_indexes/models.py b/tests/model_indexes/models.py index 69116b2650e..fbee67a1529 100644 --- a/tests/model_indexes/models.py +++ b/tests/model_indexes/models.py @@ -9,7 +9,10 @@ class Book(models.Model): isbn = models.CharField(max_length=50, db_tablespace='idx_tbls') class Meta: - indexes = [models.indexes.Index(fields=['title'])] + indexes = [ + models.indexes.Index(fields=['title']), + models.indexes.Index(fields=['isbn', 'id']), + ] class AbstractModel(models.Model): diff --git a/tests/model_indexes/tests.py b/tests/model_indexes/tests.py index 381f4fdcf8f..5f1743439c2 100644 --- a/tests/model_indexes/tests.py +++ b/tests/model_indexes/tests.py @@ -89,7 +89,7 @@ class IndexesTests(SimpleTestCase): def test_name_set(self): index_names = [index.name for index in Book._meta.indexes] - self.assertEqual(index_names, ['model_index_title_196f42_idx']) + self.assertCountEqual(index_names, ['model_index_title_196f42_idx', 'model_index_isbn_34f975_idx']) def test_abstract_children(self): index_names = [index.name for index in ChildModel1._meta.indexes]