﻿id	summary	reporter	owner	description	type	status	component	version	severity	resolution	keywords	cc	stage	has_patch	needs_docs	needs_tests	needs_better_patch	easy	ui_ux
34861	KeyTextTransform incompatible with GeneratedField	Paolo Melchiorre	Paolo Melchiorre	"Broken SQL code generated when KeyTextTransform is used in GeneratedField expression

**Steps**

Steps to reproduce the error.

**Model**

{{{#!python

from django.db import models
from django.db.models.fields.json import KT

class Response(models.Model):
    data = models.JSONField(default=dict)
    status = models.GeneratedField(
        db_persist=True,
        expression=KT(""data__status""),
        output_field=models.PositiveSmallIntegerField(),
    )
}}}

**Migration**

{{{#!bash
$ python3 -m manage makemigrations
Migrations for 'https':
  https/migrations/0001_initial.py
    - Create model Response
$ python -m manage sqlmigrate https 0001
}}}

{{{#!sql
BEGIN;
--
-- Create model Response
--
CREATE TABLE ""https_response"" (
    ""id"" bigint NOT NULL PRIMARY KEY GENERATED BY DEFAULT AS IDENTITY,
    ""data"" jsonb NOT NULL,
    ""status"" smallint GENERATED ALWAYS AS (None(""data"")) STORED
);
COMMIT;
}}}

**Traceback**


{{{#!bash
$ python -m manage migrate https 0001
}}}


{{{#!python
Operations to perform:
  Target specific migration: 0001_initial, from https
Running migrations:
  Applying https.0001_initial...Traceback (most recent call last):
  File ""/home/paulox/Projects/generatedfield/.venv/lib/python3.11/site-packages/django/db/backends/utils.py"", line 99, in _execute
    return self.cursor.execute(sql)
           ^^^^^^^^^^^^^^^^^^^^^^^^
  File ""/home/paulox/Projects/generatedfield/.venv/lib/python3.11/site-packages/psycopg/cursor.py"", line 737, in execute
    raise ex.with_traceback(None)
psycopg.errors.SyntaxError: syntax error at or near ""(""
LINE 1: ... NULL, ""status"" smallint GENERATED ALWAYS AS (None(""data"")) ...
                                                             ^
}}}

**Queryset**

Using KeyTextTransform in a query instead generates a correct SQL code.

{{{#!pycon
>>> from django.db.models.fields.json import KT
>>> from https.models import Response
>>> str(Response.objects.values_list(KT(""data__status"")).query)
'SELECT (""https_response"".""data"" ->> status) AS ""keytexttransform1"" FROM ""geometricfigures_response""'
}}}
"	Bug	closed	Database layer (models, ORM)	5.0	Release blocker	fixed	field, database, generated, output_field		Ready for checkin	1	0	0	0	0	0
