diff --git a/django/db/models/functions/comparison.py b/django/db/models/functions/comparison.py index c897fc262f..76ef5d219b 100644 --- a/django/db/models/functions/comparison.py +++ b/django/db/models/functions/comparison.py @@ -162,7 +162,8 @@ class JSONObject(Func): def join(self, args): pairs = zip(args[::2], args[1::2], strict=True) - return ", ".join([" VALUE ".join(pair) for pair in pairs]) + # Wrap 'key' in parentheses in case of postgres cast :: syntax. + return ", ".join([f"({key}) VALUE {value}" for key, value in pairs]) def as_native(self, compiler, connection, *, returning, **extra_context): return self.as_sql( @@ -174,24 +175,28 @@ class JSONObject(Func): ) def as_postgresql(self, compiler, connection, **extra_context): - if ( - not connection.features.is_postgresql_16 - or connection.features.uses_server_side_binding - ): - copy = self.copy() - copy.set_source_expressions( - [ - Cast(expression, TextField()) if index % 2 == 0 else expression - for index, expression in enumerate(copy.get_source_expressions()) - ] + # Casting keys to text is only required when using JSONB_BUILD_OBJECT + # or when using JSON_OBJECT on PostgreSQL 16+ with server-side bindings. + # This is done in all cases for consistency. + copy = self.copy() + copy.set_source_expressions( + [ + Cast(expression, TextField()) if index % 2 == 0 else expression + for index, expression in enumerate(copy.get_source_expressions()) + ] + ) + + if connection.features.is_postgresql_16: + return copy.as_native( + compiler, connection, returning="JSONB", **extra_context ) - return super(JSONObject, copy).as_sql( - compiler, - connection, - function="JSONB_BUILD_OBJECT", - **extra_context, - ) - return self.as_native(compiler, connection, returning="JSONB", **extra_context) + + return super(JSONObject, copy).as_sql( + compiler, + connection, + function="JSONB_BUILD_OBJECT", + **extra_context, + ) def as_oracle(self, compiler, connection, **extra_context): return self.as_native(compiler, connection, returning="CLOB", **extra_context)