def get_cached_trees(queryset):
 current_path = []
 top_nodes = []
 if queryset:
  parent_attr = queryset[0]._mptt_meta.parent_attr
  root_level = None
  for obj in queryset:
   node_level = obj.get_level()
   if (root_level is None):
    root_level = node_level
   if (node_level < root_level):
    raise ValueError((_(u'Node %s not in depth-first order') % (type(queryset),)))
   obj._cached_children = []
   while (len(current_path) > (node_level - root_level)):
    current_path.pop((-1))
   if (node_level == root_level):
    top_nodes.append(obj)
   else:
    _parent = current_path[(-1)]
    setattr(obj, parent_attr, _parent)
    _parent._cached_children.append(obj)
    if (root_level == 0):
     setattr(obj, u'_mptt_use_cached_ancestors', True)
   current_path.append(obj)
 return top_nodes

def get_cached_trees ( queryset ) : current_path = [ ] top_nodes = [ ] if queryset : parent_attr = queryset [ 0 ] . _mptt_meta . parent_attr root_level = None for obj in queryset : node_level = obj . get_level ( ) if ( root_level is None ) : root_level = node_level if ( node_level < root_level ) : raise ValueError ( ( _ ( u'Node %s not in depth-first order' ) % ( type ( queryset ) , ) ) ) obj . _cached_children = [ ] while ( len ( current_path ) > ( node_level - root_level ) ) : current_path . pop ( ( - 1 ) ) if ( node_level == root_level ) : top_nodes . append ( obj ) else : _parent = current_path [ ( - 1 ) ] setattr ( obj , parent_attr , _parent ) _parent . _cached_children . append ( obj ) if ( root_level == 0 ) : setattr ( obj , u'_mptt_use_cached_ancestors' , True ) current_path . append ( obj ) return top_nodes
takes a list/queryset of model objects in mptt left order and caches the children and parent on each node .