django-mptt get_descendants for a list of nodes

thedk picture thedk · Apr 19, 2011 · Viewed 9.1k times · Source

I am trying to get all descendants(include_self=True) not for one Node, but for a list (a QuerySet) of Nodes. This should be one SQL query.

Example (that actually is not working:)

some_nodes = Node.objects.filter( ...some_condition... ) 
some_nodes.get_descendants(include_self=True) #hopefully I would like 
to have all possible Nodes starting from every node of "some_nodes" 

The only idea I have right now is to iterate through some_nodes and run get_descendants() for every node - but this is terrible solution (plenty of SQL queries).

If there is no clean way to do it via Django ORM can you provide me a custom SQL to run instead? Here you can make assumption that I have a list of Node's pk.

EDIT: If that could help - all of my "some_nodes" are placed in the same parent directory and have the same "level" in the tree.

Answer

Cory picture Cory · Jan 13, 2016

Later versions of mptt already have this function built into the object manager. So the solution to this is just as follows:

Node.objects.get_queryset_descendants(my_queryset, include_self=False)