From 574ee4023e15cfb195833edfbaed353f8021c62f Mon Sep 17 00:00:00 2001 From: Paolo Melchiorre Date: Fri, 22 Sep 2023 11:27:40 +0200 Subject: [PATCH] Fixed #34861 -- Fixed crash when adding GeneratedField with some expressions. Co-authored-by: Simon Charette --- django/db/models/fields/generated.py | 8 +++----- tests/schema/tests.py | 21 ++++++++++++++++++++- 2 files changed, 23 insertions(+), 6 deletions(-) diff --git a/django/db/models/fields/generated.py b/django/db/models/fields/generated.py index deb5875638..225d3e9d12 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 e20b875a8e..340399c0bf 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):