From e3cb8bcb7d2a2d392e726ee1f7e32a8d9038e14c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Beno=C3=AEt=20Vinot?= Date: Wed, 17 Aug 2022 13:19:16 +0200 Subject: [PATCH] Fixed #33932 -- Fixed altering AutoFields to OneToOneField on PostgreSQL. Regression in 2eea361eff58dd98c409c5227064b901f41bd0d6. --- django/db/backends/postgresql/schema.py | 2 +- docs/releases/4.1.1.txt | 4 ++++ tests/schema/tests.py | 26 +++++++++++++++++++++++++ 3 files changed, 31 insertions(+), 1 deletion(-) diff --git a/django/db/backends/postgresql/schema.py b/django/db/backends/postgresql/schema.py index 633146a80b..cfc30516e6 100644 --- a/django/db/backends/postgresql/schema.py +++ b/django/db/backends/postgresql/schema.py @@ -175,7 +175,7 @@ class DatabaseSchemaEditor(BaseDatabaseSchemaEditor): self.sql_drop_indentity % { "table": self.quote_name(table), - "column": self.quote_name(strip_quotes(old_field.column)), + "column": self.quote_name(strip_quotes(new_field.column)), } ) column = strip_quotes(new_field.column) diff --git a/docs/releases/4.1.1.txt b/docs/releases/4.1.1.txt index 22b9be5bf7..39b1306234 100644 --- a/docs/releases/4.1.1.txt +++ b/docs/releases/4.1.1.txt @@ -39,3 +39,7 @@ Bugfixes * Fixed a regression in Django 4.1 that caused an incorrect migration when adding ``AutoField``, ``BigAutoField``, or ``SmallAutoField`` on PostgreSQL (:ticket:`33919`). + +* Fixed a regression in Django 4.1 that caused a migration crash on PostgreSQL + when altering ``AutoField``, ``BigAutoField``, or ``SmallAutoField`` to + ``OneToOneField`` (:ticket:`33932`). diff --git a/tests/schema/tests.py b/tests/schema/tests.py index 9e2385f5d8..c31a1d78fa 100644 --- a/tests/schema/tests.py +++ b/tests/schema/tests.py @@ -1588,6 +1588,32 @@ class SchemaTests(TransactionTestCase): # OneToOneField. self.assertEqual(counts, {"fks": expected_fks, "uniques": 1, "indexes": 0}) + def test_autofield_to_o2o(self): + with connection.schema_editor() as editor: + editor.create_model(Author) + editor.create_model(Note) + + # Rename the field. + old_field = Author._meta.get_field("id") + new_field = AutoField(primary_key=True) + new_field.set_attributes_from_name("note_ptr") + new_field.model = Author + + with connection.schema_editor() as editor: + editor.alter_field(Author, old_field, new_field, strict=True) + # Alter AutoField to OneToOneField. + new_field_o2o = OneToOneField(Note, CASCADE) + new_field_o2o.set_attributes_from_name("note_ptr") + new_field_o2o.model = Author + + with connection.schema_editor() as editor: + editor.alter_field(Author, new_field, new_field_o2o, strict=True) + columns = self.column_classes(Author) + field_type, _ = columns["note_ptr_id"] + self.assertEqual( + field_type, connection.features.introspected_field_types["IntegerField"] + ) + def test_alter_field_fk_keeps_index(self): with connection.schema_editor() as editor: editor.create_model(Author)