Subqueries should retain ORDER BY when using DISTINCT ON
|Reported by:||brianglass||Owned by:||anonymous|
|Component:||Database layer (models, ORM)||Version:||1.5|
|Has patch:||yes||Needs documentation:||no|
|Needs tests:||no||Patch needs improvement:||no|
When using subqueries in conjunction with DISTINCT ON, ordering should be retained.
Case in point: if I have a table of chapters in a book with weightings for popularity and I wish to obtain the top weighted chapter per book I might do something like:
Now I want the chapters to be ordered by weight, so I use top_chapters as a sub-query:
chapters = Chapter.objects.filter(id__in=top_chapters).order_by('weight')
However, the ORDER BY statement is stripped from the subquery so we are not guaranteed to get the top chapters. If the subquery is sliced as in the following, the ordering is retained:
count = top_chapters.count() chapters = Chapter.objects.filter(id__in=top_chapters[:count]).order_by('weight')
This issue seems related to ticket #12328. In that ticket, order by was intentionally retained if the subquery is sliced.
Change History (9)
comment:1 Changed 3 years ago by
|Patch needs improvement:||unset|