I am using django-threadedcomments, however the question also applies generally to sorting a QuerySet.
The comment objects in the QuerySet have two important fields, tree_path and submit_date. tree_path is of the form "a/b/.../z" where 'a' is the highest-order index in the tree, and 'b' is the lowest order index in the tree. So the first root comment will have a tree_path of '1'. A child of that comment will have a tree_path of '1/1'. Another child of '1' will have a tree_path of '1/2'. The second root comment will have a root_path of '2', etc...
The QuerySet "qs" is sorted like above, with comments in threaded order with the oldest comments on top. Just the tree_paths of the above example would look like [1, 1/1, 1/2, 2]. I would like to sort each level of comments with the newest comments first. So the QuerySet instead should be [2, 1, 1/2, 1/1].
How can I do this?
I can sort just the root level comments by using:
qs = qs.extra(select={ 'tree_path_root': 'SUBSTRING(tree_path, 1, 1)' })
.order_by('%stree_path_root' % ('-'), 'tree_path')
But I cannot figure out how to sort the non-root comments at the same time. I've tried something like:
qs = qs.extra(select={ 'tree_path_root': 'SUBSTRING(tree_path, 1, 1)'
'tree_path_sec' : 'SUBSTRING(tree_path, 3, 1)'})
.order_by('%stree_path_root' % ('-'), '%stree_path_sec' % ('-'), 'tree_path')
But that destroys the threading of the comments.
Any suggestions? Thanks!