mirror of
https://github.com/django/django.git
synced 2025-10-24 06:06:09 +00:00
Fixed #24245 -- Added introspection for database defaults.
Needed for tests for migrations handling of database defaults.
This commit is contained in:
@@ -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)
|
||||
|
||||
Reference in New Issue
Block a user