diff --git a/django/db/models/expressions.py b/django/db/models/expressions.py index 0d304b6ec6..43b8920d95 100644 --- a/django/db/models/expressions.py +++ b/django/db/models/expressions.py @@ -920,7 +920,7 @@ class ExpressionWrapper(Expression): return expression.get_group_by_cols(alias=alias) def as_sql(self, compiler, connection): - return self.expression.as_sql(compiler, connection) + return compiler.compile(self.expression) def __repr__(self): return "{}({})".format(self.__class__.__name__, self.expression) diff --git a/docs/releases/3.1.3.txt b/docs/releases/3.1.3.txt index 82cd523829..f1a9aaf42d 100644 --- a/docs/releases/3.1.3.txt +++ b/docs/releases/3.1.3.txt @@ -30,3 +30,7 @@ Bugfixes * Fixed a regression in Django 3.1 that caused a crash of ``__in`` lookup when using key transforms for :class:`~django.db.models.JSONField` in the lookup value (:ticket:`32096`). + +* Fixed a regression in Django 3.1 that caused a crash of + :class:`~django.db.models.ExpressionWrapper` with key transforms for + :class:`~django.db.models.JSONField` (:ticket:`32096`). diff --git a/tests/model_fields/test_jsonfield.py b/tests/model_fields/test_jsonfield.py index a590ac1221..f45589e075 100644 --- a/tests/model_fields/test_jsonfield.py +++ b/tests/model_fields/test_jsonfield.py @@ -10,7 +10,10 @@ from django.db import ( DataError, IntegrityError, NotSupportedError, OperationalError, connection, models, ) -from django.db.models import Count, F, OuterRef, Q, Subquery, Transform, Value +from django.db.models import ( + Count, ExpressionWrapper, F, IntegerField, OuterRef, Q, Subquery, + Transform, Value, +) from django.db.models.expressions import RawSQL from django.db.models.fields.json import ( KeyTextTransform, KeyTransform, KeyTransformFactory, @@ -405,6 +408,17 @@ class TestQuerying(TestCase): [self.objs[4]], ) + def test_expression_wrapper_key_transform(self): + self.assertSequenceEqual( + NullableJSONModel.objects.annotate( + expr=ExpressionWrapper( + KeyTransform('c', 'value'), + output_field=IntegerField(), + ), + ).filter(expr__isnull=False), + self.objs[3:5], + ) + def test_has_key(self): self.assertSequenceEqual( NullableJSONModel.objects.filter(value__has_key='a'),