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

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

View File

@ -302,7 +302,8 @@ class KeyTransform(Transform):
def as_postgresql(self, compiler, connection): def as_postgresql(self, compiler, connection):
lhs, params, key_transforms = self.preprocess_lhs(compiler, connection) lhs, params, key_transforms = self.preprocess_lhs(compiler, connection)
if len(key_transforms) > 1: 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: try:
lookup = int(self.key_name) lookup = int(self.key_name)
except ValueError: except ValueError:

View File

@ -14,3 +14,6 @@ Bugfixes
* Fixed passing extra HTTP headers to ``AsyncRequestFactory`` request methods * Fixed passing extra HTTP headers to ``AsyncRequestFactory`` request methods
(:ticket:`32159`). (: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

@ -408,6 +408,18 @@ class TestQuerying(TestCase):
[self.objs[4]], [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): def test_expression_wrapper_key_transform(self):
self.assertSequenceEqual( self.assertSequenceEqual(
NullableJSONModel.objects.annotate( NullableJSONModel.objects.annotate(