order_by method doesn't work
dinauu opened this issue · 2 comments
I want to sort the structure of users by username, but if I use the standard order_by
method then the sort doesn't work.
Structure.objects.all().order_by('user__username')
If we look at the query
for the resulting TreeQuerySet
, we will see that the sorting has not changed.
ORDER BY ("__tree".tree_ordering) ASC
But if we sort using the extra
method, then everything works as it should:
Structure.objects.all().extra(order_by=['user__username'])
Sorting also works if we call the order_by
method twice:
structure = Structure.objects.all()
structure = structure.order_by('user__username')
structure = structure.order_by('user__username')
The ordering behavior should definitely be documented. For now, it's just a comment in the code: https://github.com/matthiask/django-tree-queries/blob/d2475ad93bdf9208fa587bb7112c008b39a29430/tree_queries/compiler.py#L165-L169
I don't think the current structure of the CTE allows using a field on a different table for ordering while still fetching items in depth-first order. It may be necessary to copy the username
value to the Structure
model and set Meta.ordering
to ["username"]
(or something). Or you could make User
a TreeNode
. I don't think there's an easy way around it for now, sorry.
OK I understood. Thanks for the answer and for the library.