﻿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
37558	Annotation yielding sets are not filterable on PostgreSQL	David		"Annotating a queryset with an expression marked as  [https://docs.djangoproject.com/en/6.1/ref/models/expressions/#django.db.models.Expression.set_returning `set_returning = True` ] and then using the annotation in a `.filter` causes the compiler to build an invalid query on PostgreSQL because the expression is put in the `WHERE` clause instead of building a subquery.

Here is a sample code to reproduce the issue:

{{{#!python
# models.py
from django.db import models


class JsonModel(models.Model):
    data = models.JSONField(null=True)


# tests.py
from django.db import models
from django.test import TestCase

from .models import JsonModel


class JSONBPathQuery(models.Func):
    function = ""jsonb_path_query""
    arity = 1
    output_field = models.JSONField()
    set_returning = True


class SetReturningFilterTests(TestCase):

    def test_filter_on_set_returning_annotation(self):

        test_model = JsonModel.objects.create(
            data={""key"": [{""id"": 1, ""name"": ""test1""}, {""id"": 2, ""name"": ""test2""}]}, id=1
        )
        qs = JsonModel.objects.annotate(
            table_element=JSONBPathQuery(""data"", Value(""$.key[*]""))
        ).filter(table_element={""id"": 1, ""name"": ""test1""})

        # django.db.utils.NotSupportedError: set-returning functions are not allowed in WHERE
        self.assertSequenceEqual(
            qs.values_list(""table_element"", flat=True),
            [{""id"": 1, ""name"": ""test1""}],
        )
}}}

Currently annotating an expression with `set_returning = True` and then using it in a filter generates the following SQL:

{{{#!sql
SELECT jsonb_path_query(""annotations_jsonmodel"".""data"", %s) AS ""table_element""
FROM ""annotations_jsonmodel""
WHERE jsonb_path_query(""annotations_jsonmodel"".""data"", %s) = %s
}}}

While the expected SQL is:

{{{#!sql
SELECT ""qualify"".""table_element"" FROM (
  SELECT jsonb_path_query(""annotations_jsonmodel"".""data"", %s) AS ""table_element""
  FROM ""annotations_jsonmodel""
) ""qualify"" WHERE ""table_element"" = %s
}}}


NOTE: this behaviour can be achieved by using `contains_over_clause = True`, this feels strange to me: because it has a different semanthic meaning and I did not expect it to work like this since it should work with `Window`.
"	Uncategorized	new	Database layer (models, ORM)	6.1	Normal		postgres, set_returning		Unreviewed	0	0	0	0	0	0
