﻿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
33225	Missing FROM-clause when ordering by a relationship defined on the parent model in a Subquery inside a negated Q	InvalidInterrupt	Geonsang Yoo	"I encountered the following error in 3.2, and produced this test case against main (`551c997f`) today; using the postgres backend for all tests.

Using the models from `tests.model_inheritance_regress.models`, when running:
{{{
list(
    ItalianRestaurant.objects.filter(
        ~Q(
            supplier__pk__in=Subquery(
                ItalianRestaurant.objects.filter(pk=OuterRef('pk'))
                .order_by('serves_gnocchi')
                .values('pk')
            )
        )
    )
)
}}}
ProgrammingError is raised, due to a missing JOIN of `model_inheritance_regress_restaurant`.

This is as much as I was able to reduce the test case. In particular, the following seem necessary to encounter the error:
* The negation of the Q object
* The `__in` lookup passing through a relationship defined on the parent model
* The `filter()` on an `OuterRef`
* The use of `order_by()` (`distinct(*fields)` may be substituted)

The error also occurs if `values('supplier__pk')` is used as would be semantically correct.


When debugging, it appeared that the inner `Query` object had a refcount of zero for the alias in question, but I may have misunderstood what was happening there."	Bug	assigned	Database layer (models, ORM)	dev	Normal			InvalidInterrupt	Accepted	0	0	0	0	0	0
