Skip to content

Commit

Permalink
Refs #30446, Refs #34944 -- Fixed crash when adding GeneratedField wi…
Browse files Browse the repository at this point in the history
…th string Value().

This should allow smarter output_field inferring in functions dealing
with text expressions.

Regression in f333e35.
  • Loading branch information
charettes authored and felixxm committed Nov 8, 2023
1 parent 5f2f12f commit 8b1acc0
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 1 deletion.
2 changes: 1 addition & 1 deletion django/db/models/expressions.py
Original file line number Diff line number Diff line change
Expand Up @@ -1082,7 +1082,7 @@ def get_group_by_cols(self):

def _resolve_output_field(self):
if isinstance(self.value, str):
return fields.CharField()
return fields.CharField(max_length=len(self.value))
if isinstance(self.value, bool):
return fields.BooleanField()
if isinstance(self.value, int):
Expand Down
1 change: 1 addition & 0 deletions tests/expressions/tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -2227,6 +2227,7 @@ def test_resolve_output_field(self):
with self.subTest(type=type(value)):
expr = Value(value)
self.assertIsInstance(expr.output_field, output_field_type)
self.assertEqual(Value("foo").output_field.max_length, 3)

def test_resolve_output_field_failure(self):
msg = "Cannot resolve expression type, unknown output_field"
Expand Down
17 changes: 17 additions & 0 deletions tests/schema/tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -842,6 +842,23 @@ class Meta:
False,
)

@isolate_apps("schema")
@skipUnlessDBFeature("supports_stored_generated_columns")
def test_add_generated_field_with_string_value(self):
class GeneratedFieldStringValueModel(Model):
value = GeneratedField(expression=Value("static string"), db_persist=True)

class Meta:
app_label = "schema"

with CaptureQueriesContext(connection) as ctx:
with connection.schema_editor() as editor:
editor.create_model(GeneratedFieldStringValueModel)
self.assertIs(
any("None" in query["sql"] for query in ctx.captured_queries),
False,
)

@isolate_apps("schema")
@skipUnlessDBFeature("supports_stored_generated_columns")
def test_add_generated_field_with_output_field(self):
Expand Down

0 comments on commit 8b1acc0

Please sign in to comment.