Sfoglia il codice sorgente

Fixed #28597 -- Fixed crash with the name of a model's autogenerated primary key in an Index's fields.

Mariusz Felisiak 7 anni fa
parent
commit
fb02ebe889

+ 7 - 6
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

+ 3 - 0
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`).

+ 4 - 1
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):

+ 1 - 1
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]