diff --git a/django/db/models/fields/generated.py b/django/db/models/fields/generated.py index deb5875638c..225d3e9d121 100644 --- a/django/db/models/fields/generated.py +++ b/django/db/models/fields/generated.py @@ -61,12 +61,10 @@ class GeneratedField(Field): self.register_lookup(lookup, lookup_name=lookup_name) def generated_sql(self, connection): - return self._resolved_expression.as_sql( - compiler=connection.ops.compiler("SQLCompiler")( - self._query, connection=connection, using=None - ), - connection=connection, + compiler = connection.ops.compiler("SQLCompiler")( + self._query, connection=connection, using=None ) + return compiler.compile(self._resolved_expression) def check(self, **kwargs): databases = kwargs.get("databases") or [] diff --git a/tests/schema/tests.py b/tests/schema/tests.py index e20b875a8ec..340399c0bfb 100644 --- a/tests/schema/tests.py +++ b/tests/schema/tests.py @@ -32,6 +32,7 @@ from django.db.models import ( FloatField, ForeignKey, ForeignObject, + GeneratedField, Index, IntegerField, JSONField, @@ -50,7 +51,7 @@ from django.db.models import ( UUIDField, Value, ) -from django.db.models.fields.json import KeyTextTransform +from django.db.models.fields.json import KT, KeyTextTransform from django.db.models.functions import Abs, Cast, Collate, Lower, Random, Upper from django.db.models.indexes import IndexExpression from django.db.transaction import TransactionManagementError, atomic @@ -810,6 +811,24 @@ class SchemaTests(TransactionTestCase): # Introspection treats BLOBs as TextFields self.assertEqual(columns["bits"][0], "TextField") + @isolate_apps("schema") + @skipUnlessDBFeature("supports_json_field", "supports_stored_generated_columns") + def test_add_generated_field_with_kt_model(self): + class GeneratedFieldKTModel(Model): + data = JSONField() + status = GeneratedField(expression=KT("data__status"), db_persist=True) + + class Meta: + app_label = "schema" + + with CaptureQueriesContext(connection) as ctx: + with connection.schema_editor() as editor: + editor.create_model(GeneratedFieldKTModel) + self.assertIs( + any("None" in query["sql"] for query in ctx.captured_queries), + False, + ) + @isolate_apps("schema") def test_add_auto_field(self): class AddAutoFieldModel(Model):