[3.1.x] Fixed #32182 -- Fixed crash of JSONField nested key transforms with subquery annotations on PostgreSQL.

Backport of 0773837e15 from master
This commit is contained in:
Hannes Ljungberg 2020-11-09 17:54:20 +01:00 committed by Mariusz Felisiak
parent d67f965c79
commit cc3870c30f
3 changed files with 17 additions and 1 deletions

View File

@ -302,7 +302,8 @@ class KeyTransform(Transform):
def as_postgresql(self, compiler, connection):
lhs, params, key_transforms = self.preprocess_lhs(compiler, connection)
if len(key_transforms) > 1:
return '(%s %s %%s)' % (lhs, self.postgres_nested_operator), params + [key_transforms]
sql = '(%s %s %%s)' % (lhs, self.postgres_nested_operator)
return sql, tuple(params) + (key_transforms,)
try:
lookup = int(self.key_name)
except ValueError:

View File

@ -14,3 +14,6 @@ Bugfixes
* Fixed passing extra HTTP headers to ``AsyncRequestFactory`` request methods
(:ticket:`32159`).
* Fixed crash of key transforms for :class:`~django.db.models.JSONField` on
PostgreSQL when using on a ``Subquery()`` annotation (:ticket:`32182`).

View File

@ -385,6 +385,18 @@ class TestQuerying(TestCase):
[self.objs[4]],
)
def test_nested_key_transform_on_subquery(self):
self.assertSequenceEqual(
NullableJSONModel.objects.filter(value__d__0__isnull=False).annotate(
subquery_value=Subquery(
NullableJSONModel.objects.filter(pk=OuterRef('pk')).values('value')
),
key=KeyTransform('d', 'subquery_value'),
chain=KeyTransform('f', KeyTransform('1', 'key')),
).filter(chain='g'),
[self.objs[4]],
)
def test_expression_wrapper_key_transform(self):
self.assertSequenceEqual(
NullableJSONModel.objects.annotate(