| 20 | | It looks like the issue is that [https://github.com/django/django/blob/7e978fdc4228eb44cf97cb4243adc7b7bfd586c7/django/db/models/sql/query.py#L439-L443 we clear the ordering when we shouldn't] on the `.count()`. I think the logic needs to be adjusted to branch of `not self.distinct` instead of `self.distinct_fields`. |
| | 20 | It looks like the issue is that [https://github.com/django/django/blob/7e978fdc4228eb44cf97cb4243adc7b7bfd586c7/django/db/models/sql/query.py#L439-L443 we clear the ordering when we shouldn't] on the `.count()`. I think the logic needs to be adjusted to branch of `not self.distinct` instead of `self.distinct_fields`. Thing is switching this line generate this really nasty double nested query |
| | 21 | |
| | 22 | {{{#!sql |
| | 23 | SELECT COUNT(*) FROM ( |
| | 24 | SELECT "machine", "cluster" FROM ( |
| | 25 | SELECT DISTINCT "machine", "cluster", "ordering" FROM "resources" ORDER BY "ordering" ASC subquery |
| | 26 | )) subquery |
| | 27 | }}} |
| | 28 | |
| | 29 | Ideally we'd want |
| | 30 | |
| | 31 | {{{#!sql |
| | 32 | SELECT COUNT(*) FROM (SELECT DISTINCT "machine", "cluster", "ordering" FROM "resources") subquery |
| | 33 | }}} |
| | 34 | |
| | 35 | Where the `ORDER BY` is cleared as it's not necessary but the columns that would have made it to `SELECT` clause to satisfy the `DISTINCT`/`ORDER BY` rule are all included. |