mirror of
https://github.com/django/django.git
synced 2025-10-24 14:16:09 +00:00
Fixed #22581: Pass default values for schema through get_db_prep_save()
This commit is contained in:
@@ -231,6 +231,40 @@ class SchemaTests(TransactionTestCase):
|
||||
else:
|
||||
self.assertEqual(field_type, 'BooleanField')
|
||||
|
||||
def test_add_field_default_transform(self):
|
||||
"""
|
||||
Tests adding fields to models with a default that is not directly
|
||||
valid in the database (#22581)
|
||||
"""
|
||||
class TestTransformField(IntegerField):
|
||||
# Weird field that saves the count of items in its value
|
||||
def get_default(self):
|
||||
return self.default
|
||||
def get_prep_value(self, value):
|
||||
if value is None:
|
||||
return 0
|
||||
return len(value)
|
||||
# Create the table
|
||||
with connection.schema_editor() as editor:
|
||||
editor.create_model(Author)
|
||||
# Add some rows of data
|
||||
Author.objects.create(name="Andrew", height=30)
|
||||
Author.objects.create(name="Andrea")
|
||||
# Add the field with a default it needs to cast (to string in this case)
|
||||
new_field = TestTransformField(default={1:2})
|
||||
new_field.set_attributes_from_name("thing")
|
||||
with connection.schema_editor() as editor:
|
||||
editor.add_field(
|
||||
Author,
|
||||
new_field,
|
||||
)
|
||||
# Ensure the field is there
|
||||
columns = self.column_classes(Author)
|
||||
field_type, field_info = columns['thing']
|
||||
self.assertEqual(field_type, 'IntegerField')
|
||||
# Make sure the values were transformed correctly
|
||||
self.assertEqual(Author.objects.extra(where=["thing = 1"]).count(), 2)
|
||||
|
||||
def test_alter(self):
|
||||
"""
|
||||
Tests simple altering of fields
|
||||
|
||||
Reference in New Issue
Block a user