فهرست منبع

Refs #30446, Refs #34944 -- Fixed crash when adding GeneratedField with string Value().

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

Regression in f333e3513e8bdf5ffeb6eeb63021c230082e6f95.
Simon Charette 1 سال پیش
والد
کامیت
8b1acc0440
3فایلهای تغییر یافته به همراه19 افزوده شده و 1 حذف شده
  1. 1 1
      django/db/models/expressions.py
  2. 1 0
      tests/expressions/tests.py
  3. 17 0
      tests/schema/tests.py

+ 1 - 1
django/db/models/expressions.py

@@ -1082,7 +1082,7 @@ class Value(SQLiteNumericMixin, Expression):
 
     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):

+ 1 - 0
tests/expressions/tests.py

@@ -2227,6 +2227,7 @@ class ValueTests(TestCase):
             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"

+ 17 - 0
tests/schema/tests.py

@@ -842,6 +842,23 @@ class SchemaTests(TransactionTestCase):
             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):