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 20600 Subqueries should retain ORDER BY when using DISTINCT ON brianglass anonymous "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: {{{ #!python top_chapters = Chapter.objects.filter(topics__in=['css', 'javascript']).distinct('book_id').order_by('book_id', '-weight', 'id) }}} Now I want the chapters to be ordered by weight, so I use top_chapters as a sub-query: {{{ #!python 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: {{{ #!python 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." Bug closed Database layer (models, ORM) 1.5 Normal fixed Accepted 1 0 0 0 0 0