Skip to content

Commit 0890473

Browse files
Andriy Sokolovskiytimgraham
Andriy Sokolovskiy
authored andcommitted
Fixed #23987 -- Made SQLite SchemaEditor always use effective_default().
1 parent 222699d commit 0890473

File tree

3 files changed

+31
-2
lines changed

3 files changed

+31
-2
lines changed

django/db/backends/sqlite3/schema.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -69,8 +69,8 @@ def _remake_table(self, model, create_fields=[], delete_fields=[], alter_fields=
6969
# Add in any created fields
7070
for field in create_fields:
7171
body[field.name] = field
72-
# If there's a default, insert it into the copy map
73-
if field.has_default():
72+
# Choose a default and insert it into the copy map
73+
if not isinstance(field, ManyToManyField):
7474
mapping[field.column] = self.quote_value(
7575
self.effective_default(field)
7676
)

docs/releases/1.7.2.txt

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -135,3 +135,8 @@ Bugfixes
135135
growth in Django's own test suite (:ticket:`23969`).
136136

137137
* Fixed timesince filter translations in Korean (:ticket:`23989`).
138+
139+
* Fixed the SQLite ``SchemaEditor`` to properly add defaults in the absence of
140+
a user specified ``default``. For example, a ``CharField`` with ``blank=True``
141+
didn't set existing rows to an empty string which resulted in a crash when
142+
adding the ``NOT NULL`` constraint (:ticket:`23987`).

tests/schema/tests.py

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1173,3 +1173,27 @@ def get_field(*args, **kwargs):
11731173
}
11741174
)
11751175
editor.alter_field(model, get_field(Author, field_class=ForeignKey), field)
1176+
1177+
def test_add_field_use_effective_default(self):
1178+
"""
1179+
#23987 - effective_default() should be used as the field default when
1180+
adding a new field.
1181+
"""
1182+
# Create the table
1183+
with connection.schema_editor() as editor:
1184+
editor.create_model(Author)
1185+
# Ensure there's no surname field
1186+
columns = self.column_classes(Author)
1187+
self.assertNotIn("surname", columns)
1188+
# Create a row
1189+
Author.objects.create(name='Anonymous1')
1190+
# Add new CharField to ensure default will be used from effective_default
1191+
new_field = CharField(max_length=15, blank=True)
1192+
new_field.set_attributes_from_name("surname")
1193+
with connection.schema_editor() as editor:
1194+
editor.add_field(Author, new_field)
1195+
# Ensure field was added with the right default
1196+
with connection.cursor() as cursor:
1197+
cursor.execute("SELECT surname FROM schema_author;")
1198+
item = cursor.fetchall()[0]
1199+
self.assertEqual(item[0], '')

0 commit comments

Comments
 (0)