From 089047331d972c0ee58d13476fc54f2118bf1359 Mon Sep 17 00:00:00 2001 From: Andriy Sokolovskiy Date: Mon, 15 Dec 2014 16:14:39 +0200 Subject: [PATCH] Fixed #23987 -- Made SQLite SchemaEditor always use effective_default(). --- django/db/backends/sqlite3/schema.py | 4 ++-- docs/releases/1.7.2.txt | 5 +++++ tests/schema/tests.py | 24 ++++++++++++++++++++++++ 3 files changed, 31 insertions(+), 2 deletions(-) diff --git a/django/db/backends/sqlite3/schema.py b/django/db/backends/sqlite3/schema.py index 0ac2f25e04..9aeca56bf7 100644 --- a/django/db/backends/sqlite3/schema.py +++ b/django/db/backends/sqlite3/schema.py @@ -69,8 +69,8 @@ class DatabaseSchemaEditor(BaseDatabaseSchemaEditor): # Add in any created fields for field in create_fields: body[field.name] = field - # If there's a default, insert it into the copy map - if field.has_default(): + # Choose a default and insert it into the copy map + if not isinstance(field, ManyToManyField): mapping[field.column] = self.quote_value( self.effective_default(field) ) diff --git a/docs/releases/1.7.2.txt b/docs/releases/1.7.2.txt index 60e4c15e50..2f49d7d889 100644 --- a/docs/releases/1.7.2.txt +++ b/docs/releases/1.7.2.txt @@ -135,3 +135,8 @@ Bugfixes growth in Django's own test suite (:ticket:`23969`). * Fixed timesince filter translations in Korean (:ticket:`23989`). + +* Fixed the SQLite ``SchemaEditor`` to properly add defaults in the absence of + a user specified ``default``. For example, a ``CharField`` with ``blank=True`` + didn't set existing rows to an empty string which resulted in a crash when + adding the ``NOT NULL`` constraint (:ticket:`23987`). diff --git a/tests/schema/tests.py b/tests/schema/tests.py index 4e11c2696a..ee93de8596 100644 --- a/tests/schema/tests.py +++ b/tests/schema/tests.py @@ -1173,3 +1173,27 @@ class SchemaTests(TransactionTestCase): } ) editor.alter_field(model, get_field(Author, field_class=ForeignKey), field) + + def test_add_field_use_effective_default(self): + """ + #23987 - effective_default() should be used as the field default when + adding a new field. + """ + # 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 to ensure default will be used from effective_default + new_field = CharField(max_length=15, blank=True) + 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], '')