diff options
Diffstat (limited to 'tests')
| -rw-r--r-- | tests/schema/tests.py | 50 |
1 files changed, 50 insertions, 0 deletions
diff --git a/tests/schema/tests.py b/tests/schema/tests.py index 2dd56d7248..12fac76579 100644 --- a/tests/schema/tests.py +++ b/tests/schema/tests.py @@ -1348,3 +1348,53 @@ class SchemaTests(TransactionTestCase): finally: # Cleanup model states AuthorWithM2M._meta.local_many_to_many.remove(new_field) + + def test_add_field_default_dropped(self): + # Create the table + with connection.schema_editor() as editor: + editor.create_model(Author) + # Ensure there's no surname field + columns = self.column_classes(Author) + self.assertNotIn("surname", columns) + # Create a row + Author.objects.create(name='Anonymous1') + # Add new CharField with a default + new_field = CharField(max_length=15, blank=True, default='surname default') + new_field.set_attributes_from_name("surname") + with connection.schema_editor() as editor: + editor.add_field(Author, new_field) + # Ensure field was added with the right default + with connection.cursor() as cursor: + cursor.execute("SELECT surname FROM schema_author;") + item = cursor.fetchall()[0] + self.assertEqual(item[0], 'surname default') + # And that the default is no longer set in the database. + field = next( + f for f in connection.introspection.get_table_description(cursor, "schema_author") + if f.name == "surname" + ) + if connection.features.can_introspect_default: + self.assertIsNone(field.default) + + def test_alter_field_default_dropped(self): + # Create the table + with connection.schema_editor() as editor: + editor.create_model(Author) + # Create a row + Author.objects.create(name='Anonymous1') + self.assertEqual(Author.objects.get().height, None) + old_field = Author._meta.get_field('height') + # The default from the new field is used in updating existing rows. + new_field = IntegerField(blank=True, default=42) + new_field.set_attributes_from_name('height') + with connection.schema_editor() as editor: + editor.alter_field(Author, old_field, new_field) + self.assertEqual(Author.objects.get().height, 42) + # The database default should be removed. + with connection.cursor() as cursor: + field = next( + f for f in connection.introspection.get_table_description(cursor, "schema_author") + if f.name == "height" + ) + if connection.features.can_introspect_default: + self.assertIsNone(field.default) |
