From c3ca6075cc0ad425bcf905fe14062f38eb9fbcbf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gast=C3=B3n=20Avila?= Date: Wed, 4 Sep 2024 17:32:40 -0300 Subject: [PATCH] Fixed #35732 -- Wrapped ConcatPair expression in parentheses to ensure operator precedence. When ConcatPair was updated to use || this lost the implicit wrapping from CONCAT(...). This broke the WHERE clauses when used in combination with PostgreSQL trigram similarity. Regression in 6364b6ee1071381eb3a23ba6b821fc0d6f0fce75. Co-authored-by: Emiliano Cuenca <106986074+emicuencac@users.noreply.github.com> --- django/db/models/functions/text.py | 2 +- docs/releases/5.1.2.txt | 4 +++- tests/postgres_tests/test_trigram.py | 18 ++++++++++++++++++ 3 files changed, 22 insertions(+), 2 deletions(-) diff --git a/django/db/models/functions/text.py b/django/db/models/functions/text.py index df826ffdb5..9c48659bf9 100644 --- a/django/db/models/functions/text.py +++ b/django/db/models/functions/text.py @@ -78,7 +78,7 @@ class ConcatPair(Func): return super(ConcatPair, coalesced).as_sql( compiler, connection, - template="%(expressions)s", + template="(%(expressions)s)", arg_joiner=" || ", **extra_context, ) diff --git a/docs/releases/5.1.2.txt b/docs/releases/5.1.2.txt index 234c9e0bd5..1cf3f9df09 100644 --- a/docs/releases/5.1.2.txt +++ b/docs/releases/5.1.2.txt @@ -9,4 +9,6 @@ Django 5.1.2 fixes several bugs in 5.1.1. Bugfixes ======== -* ... +* Fixed a regression in Django 5.1 that caused a crash when using the + PostgreSQL lookup :lookup:`trigram_similar` on output fields from ``Concat`` + (:ticket:`35732`). diff --git a/tests/postgres_tests/test_trigram.py b/tests/postgres_tests/test_trigram.py index 812403a324..b6c88c38a6 100644 --- a/tests/postgres_tests/test_trigram.py +++ b/tests/postgres_tests/test_trigram.py @@ -1,3 +1,6 @@ +from django.db.models import F, Value +from django.db.models.functions import Concat + from . import PostgreSQLTestCase from .models import CharFieldModel, TextFieldModel @@ -149,6 +152,21 @@ class TrigramTest(PostgreSQLTestCase): ], ) + def test_trigram_concat_precedence(self): + search_term = "im matthew" + self.assertSequenceEqual( + self.Model.objects.annotate( + concat_result=Concat( + Value("I'm "), + F("field"), + output_field=self.Model._meta.get_field("field"), + ), + ) + .filter(concat_result__trigram_similar=search_term) + .values("field"), + [{"field": "Matthew"}], + ) + class TrigramTextFieldTest(TrigramTest): """