diff --git a/django/db/models/base.py b/django/db/models/base.py index 5067fb9e4f..cf8f44919c 100644 --- a/django/db/models/base.py +++ b/django/db/models/base.py @@ -306,12 +306,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 @@ -371,6 +365,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) def _requires_legacy_default_manager(cls): # RemovedInDjango20Warning diff --git a/docs/releases/1.11.6.txt b/docs/releases/1.11.6.txt index cc8e1bfa59..ff9d4385fe 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 6d74ad8fa6..0fa998843e 100644 --- a/tests/model_indexes/models.py +++ b/tests/model_indexes/models.py @@ -5,9 +5,13 @@ class Book(models.Model): title = models.CharField(max_length=50) author = models.CharField(max_length=50) pages = models.IntegerField(db_column='page_count') + 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 c0f5a84fdb..74c7cf45f4 100644 --- a/tests/model_indexes/tests.py +++ b/tests/model_indexes/tests.py @@ -85,7 +85,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]