feincms / django-tree-queries

Adjacency-list trees for Django using recursive common table expressions. Supports PostgreSQL, sqlite, MySQL and MariaDB.
https://django-tree-queries.readthedocs.io/
BSD 3-Clause "New" or "Revised" License
433 stars 27 forks source link

order_by method doesn't work #23

Closed dinauu closed 2 years ago

dinauu commented 3 years ago

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')
matthiask commented 3 years ago

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.

dinauu commented 3 years ago

OK I understood. Thanks for the answer and for the library.