diff --git a/django/db/models/base.py b/django/db/models/base.py index 4673920ade..e4ef6e5495 100644 --- a/django/db/models/base.py +++ b/django/db/models/base.py @@ -293,14 +293,15 @@ class ModelBase(type): else: new_class.add_to_class(field.name, copy.deepcopy(field)) - if base_meta and base_meta.abstract and not abstract: - 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) + # 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 diff --git a/docs/releases/1.11.3.txt b/docs/releases/1.11.3.txt index 7085b02669..de6def5aa1 100644 --- a/docs/releases/1.11.3.txt +++ b/docs/releases/1.11.3.txt @@ -23,3 +23,6 @@ Bugfixes (:ticket:`28202`). * Fixed invalid HTML for a required ``AdminFileWidget`` (:ticket:`28278`). + +* Fixed model initialization to set the name of class-based model indexes + for models that only inherit ``models.Model`` (:ticket:`28282`). diff --git a/tests/model_indexes/models.py b/tests/model_indexes/models.py index 34b3f3246c..6d74ad8fa6 100644 --- a/tests/model_indexes/models.py +++ b/tests/model_indexes/models.py @@ -6,6 +6,9 @@ class Book(models.Model): author = models.CharField(max_length=50) pages = models.IntegerField(db_column='page_count') + class Meta: + indexes = [models.indexes.Index(fields=['title'])] + class AbstractModel(models.Model): name = models.CharField(max_length=50) diff --git a/tests/model_indexes/tests.py b/tests/model_indexes/tests.py index 791233daf0..c0f5a84fdb 100644 --- a/tests/model_indexes/tests.py +++ b/tests/model_indexes/tests.py @@ -83,6 +83,10 @@ class IndexesTests(SimpleTestCase): self.assertIsNot(index, new_index) self.assertEqual(index.fields, new_index.fields) + def test_name_set(self): + index_names = [index.name for index in Book._meta.indexes] + self.assertEqual(index_names, ['model_index_title_196f42_idx']) + def test_abstract_children(self): index_names = [index.name for index in ChildModel1._meta.indexes] self.assertEqual(index_names, ['model_index_name_440998_idx'])