I'm the one who reported that issue. This is my usecase:
I have a table T like this:
pk: Primary Key (btree indexed)
value: double (btree indexed)
group1_id: Integer (btree indexed)
group2_id: Integer (btree indexed)
...
I'm querying the table for `MIN(pk), ARRAY_AGG(ARRAY(group_id, value,t1,t2))` group by `group1_id, group2_id` for example but i need to order it by value of column value in rows that meat some condition (group_id1=x, group_id2=y). So I need to left join the main query with a subquery that extracts above mentioned rows (group_id1=x, groupid2=y) and order the main query by the value column of this query.
The table contains around ~170,000,000 rows and counting and this is the only method I found that I can get the result in reasonable time.
Currently I'm doing it in Django like this:
1. Generate main query via Django ORM.
2. Filter and order it with Rest Framework Filters.
3. Extract the sql code via `sql_with_params()`
4. Generate the subquery via Django ORM too.
5. Filter it with Rest Framework Fitlers too.
6. Extract the sql code of the subquery too.
7. Use `re.sub` to inject the join into main query (`re.sub(' WHERE ', ' LEFT OUTER JOIN ({}) AS "order_query" ON ("t"."id"="order_query"."id" etc`
8. Use `re.sub` to inject the order among other orders in main query, I have other orders too and the order of these orders are dynamic based on user request so I have to find the position of this order among the orders RestFramework generated via Django ORM.
9 And at the end I have:
```
queryset.__class__ = type(
type(queryset).__name__,
(type(queryset),),
{'__len__': lambda self: count},
)
```
So that rest framework doesn't complain about the lake of length in the returned query.
Even if Django had a way so that I could promise my query generates compatible with its ORM results this process would be easier.
In the next level it would be great if I could have the whole query structure in Django ORM api.