SQL query to avoid fetching the entire nested set when parts of it are collapsed by the user
I am trying to link django-mptt and contrib.admin together by providing something friendlier than a flat list in admin. Since the trees need to be large (otherwise I wouldn't use nested sets), users should be able to expand and collapse parts of it.
When a user expands or collapses or expands on a branch (using ajax for this), a cookie is also set containing a list with a collapse, separated by commas. This way, next time this user visits admin for my django-mptt based model, I can show him the tree in the exact state he left. Now I would like to use this list of collapsed branches to ease the load on my database by fetching only the parts of the tree I need.
Is there a way to do this efficiently? The solutions I googled were making the request for each branch, so they could avoid the requests when the branch was collapsed, but that doesn't look very efficient to me. Perhaps this is possible with a fixed number of requests?
a source to share
You don't really explain what you are doing, so it's a bit difficult to help. (What do you do with the tree? How do you display it? What do you want users to be able to do?)
Every element in the Django-MPTT tree has a method get_children()
- and using an optional parameter include_self=True
, you can get a list of the element and all of its children. You can use this to pre-filter subtrees so that you only display parts of it if you need to.
If you want users to be able to dynamically expand and collapse parts of the tree without reloading the page, you will need to use AJAX. There are various AJAX supported TreeView controls - I wrote one myself using jQuery and no doubt one of them will do something according to what you want.
a source to share