Commits

Gustavo Picon committed cbecc9c

Cleanup and small refactorings.

  • Participants
  • Parent commits 31dbf1a

Comments (0)

Files changed (6)

File treebeard/al_tree.py

 
     def get_query_set(self):
         """Sets the custom queryset as the default."""
-        qset = super(AL_NodeManager, self).get_query_set()
         if self.model.node_order_by:
             order_by = ['parent'] + list(self.model.node_order_by)
         else:
             order_by = ['parent', 'sib_order']
-        return qset.order_by(*order_by)
+        return super(AL_NodeManager, self).get_query_set().order_by(*order_by)
 
 
 class AL_Node(Node):
         ancestors = []
         node = self.parent
         while node:
-            ancestors.append(node)
+            ancestors.insert(0, node)
             node = node.parent
-        ancestors.reverse()
         return ancestors
 
     def get_root(self):
         return newobj
 
     @classmethod
-    def _get_tree_recur(cls, ret, parent, depth):
+    def _get_tree_recursively(cls, results, parent, depth):
         if parent:
-            qset = cls.objects.filter(parent=parent)
+            nodes = parent.get_children()
         else:
-            qset = cls.get_root_nodes()
-        for node in qset:
+            nodes = cls.get_root_nodes()
+        for node in nodes:
             node._cached_depth = depth
-            ret.append(node)
-            cls._get_tree_recur(ret, node, depth + 1)
+            results.append(node)
+            cls._get_tree_recursively(results, node, depth + 1)
 
     @classmethod
     def get_tree(cls, parent=None):
         """
         if parent:
             depth = parent.get_depth() + 1
-            ret = [parent]
+            results = [parent]
         else:
             depth = 1
-            ret = []
-        cls._get_tree_recur(ret, parent, depth)
-        return ret
+            results = []
+        cls._get_tree_recursively(results, parent, depth)
+        return results
 
     def get_descendants(self):
         """
     def add_sibling(self, pos=None, **kwargs):
         """Adds a new node as a sibling to the current node object."""
 
-        pos = self._fix_add_sibling_opts(pos)
+        pos = self._prepare_pos_var_for_add_sibling(pos)
 
         stmts = []
 
         newobj = self.__class__(**kwargs)
 
         if not self.node_order_by:
-            newobj.sib_order = self.__class__._move_add_sibling_aux(
-                pos, self, stmts)
+            newobj.sib_order = \
+                self.__class__._make_hole_between_siblings_for_node(pos,
+                                                                    self,
+                                                                    stmts)
 
         if self.parent_id:
             newobj.parent_id = self.parent_id
         return newobj
 
     @classmethod
-    def _move_add_sibling_aux(cls, pos, target, stmts):
+    def _make_hole_between_siblings_for_node(cls, pos, target, stmts):
         """
         helper that makes a hole between siblings for a new node (only for not
         sorted trees)
         relative to another node.
         """
 
-        pos = self._fix_move_opts(pos)
+        pos = self._prepare_pos_var_for_move(pos)
 
         stmts = []
         sib_order = None
             if sib_order:
                 self.sib_order = sib_order
             else:
-                self.sib_order = self.__class__._move_add_sibling_aux(pos,
-                                                                      target,
-                                                                      stmts)
+                self.sib_order = \
+                    self.__class__._make_hole_between_siblings_for_node(pos,
+                                                                        target,
+                                                                        stmts)
             if parent:
                 self.parent = parent
             else:

File treebeard/forms.py

             opts.model = type(instance)
         self.is_sorted = (hasattr(opts.model, 'node_order_by') and
                           opts.model.node_order_by)
-        #self.is_sorted = (len(opts.model.node_order_by) > 0)
 
         if self.is_sorted:
             choices_sort_mode = self.__class__.__position_choices_sorted

File treebeard/models.py

             A `list` (**NOT** a Queryset) of node objects with an extra
             attribute: `descendants_count`.
         """
-
-        # this is the slowest possible implementation, subclasses should do
-        # better
         if parent is None:
             qset = cls.get_root_nodes()
         else:
 
     def get_children_count(self):
         """:returns: The number of the node's children"""
-
-        # this is the last resort, subclasses of Node should implement this in
-        # a efficient way.
         return self.get_children().count()
 
     def get_descendants(self):
             The previous node's sibling, or None if it was the leftmost
             sibling.
         """
-
         siblings = self.get_siblings()
         ids = [obj.pk for obj in siblings]
         if self.pk in ids:
 
             The node that will be checked as a sibling
         """
-        return len(self.get_siblings().filter(pk__in=[node.pk])) > 0
+        return self.get_siblings().filter(pk=node.pk).exists()
 
     def is_child_of(self, node):
         """
 
             The node that will be checked as a parent
         """
-        return len(node.get_children().filter(pk__in=[self.pk])) > 0
+        return node.get_children().filter(pk=self.pk).exists()
 
     def is_descendant_of(self, node):  # pragma: no cover
         """
 
     def is_root(self):
         """:returns: True if the node is a root node (else, returns False)"""
-        return self.get_root() == self
+        return self.get_root().pk == self.pk
 
     def is_leaf(self):
         """:returns: True if the node is a leaf node (else, returns False)"""
-        return self.get_children_count() == 0
+        return not self.get_children().exists()
 
     def get_ancestors(self):  # pragma: no cover
         """
         """Removes a node and all it's descendants."""
         self.__class__.objects.filter(id=self.pk).delete()
 
-    def _fix_add_sibling_opts(self, pos):
-        """prepare the pos variable for the add_sibling method"""
+
+    def _prepare_pos_var(self, pos, method_name, valid_pos,
+                                valid_sorted_pos):
         if pos is None:
             if self.node_order_by:
                 pos = 'sorted-sibling'
             else:
                 pos = 'last-sibling'
-        if pos not in ('first-sibling', 'left', 'right', 'last-sibling',
-                       'sorted-sibling'):
+        if pos not in valid_pos:
             raise InvalidPosition('Invalid relative position: %s' % (pos, ))
-        if self.node_order_by and pos != 'sorted-sibling':
-            raise InvalidPosition('Must use %s in add_sibling when'
-                                  ' node_order_by is enabled' % (
-                                      'sorted-sibling', ))
-        if pos == 'sorted-sibling' and not self.node_order_by:
+        if self.node_order_by and pos not in valid_sorted_pos:
+            raise InvalidPosition(
+                'Must use %s in %s when node_order_by is enabled' % (
+                    ' or '.join(valid_sorted_pos), method_name))
+        if pos in valid_sorted_pos and not self.node_order_by:
             raise MissingNodeOrderBy('Missing node_order_by attribute.')
         return pos
 
-    def _fix_move_opts(self, pos):
-        """prepare the pos var for the move method"""
-        if pos is None:
-            if self.node_order_by:
-                pos = 'sorted-sibling'
-            else:
-                pos = 'last-sibling'
-        if pos not in ('first-sibling', 'left', 'right', 'last-sibling',
-                       'sorted-sibling', 'first-child', 'last-child',
-                       'sorted-child'):
-            raise InvalidPosition('Invalid relative position: %s' % (pos, ))
-        if self.node_order_by and pos not in ('sorted-child',
-                                              'sorted-sibling'):
-            raise InvalidPosition('Must use %s or %s in add_sibling when'
-                                  ' node_order_by is enabled' % (
-                                      'sorted-sibling', 'sorted-child'))
-        if (
-                pos in ('sorted-child', 'sorted-sibling') and
-                not self.node_order_by
-        ):
-            raise MissingNodeOrderBy('Missing node_order_by attribute.')
-        return pos
+    _valid_pos_for_add_sibling = ('first-sibling', 'left', 'right',
+                                  'last-sibling', 'sorted-sibling')
+    _valid_pos_for_sorted_add_sibling = ('sorted-sibling',)
+
+    def _prepare_pos_var_for_add_sibling(self, pos):
+        return self._prepare_pos_var(
+            pos,
+            'add_sibling',
+            self._valid_pos_for_add_sibling,
+            self._valid_pos_for_sorted_add_sibling)
+
+    _valid_pos_for_move = _valid_pos_for_add_sibling + (
+        'first-child', 'last-child', 'sorted-child')
+    _valid_pos_for_sorted_move = _valid_pos_for_sorted_add_sibling + (
+        'sorted-child',)
+
+    def _prepare_pos_var_for_move(self, pos):
+        return self._prepare_pos_var(
+            pos,
+            'move',
+            self._valid_pos_for_move,
+            self._valid_pos_for_sorted_move)
 
     def get_sorted_pos_queryset(self, siblings, newobj):
         """
 
         result, info = [], {}
         start_depth, prev_depth = (None, None)
-
         for node in cls.get_tree(parent):
             depth = node.get_depth()
-
             if start_depth is None:
                 start_depth = depth
-
             open = (depth and (prev_depth is None or depth > prev_depth))
-
             if prev_depth is not None and depth < prev_depth:
                 info['close'] = list(range(0, prev_depth - depth))
-
             info = {'open': open, 'close': [], 'level': depth - start_depth}
-
             result.append((node, info,))
-
             prev_depth = depth
-
         if start_depth and start_depth > 0:
             info['close'] = list(range(0, prev_depth - start_depth + 1))
-
         return result
 
     @classmethod

File treebeard/mp_tree.py

            node's new position
         """
 
-        pos = self._fix_add_sibling_opts(pos)
+        pos = self._prepare_pos_var_for_add_sibling(pos)
 
         # creating a new object
         newobj = self.__class__(**kwargs)
         """:returns: the root node for the current node object."""
         return self.__class__.objects.get(path=self.path[0:self.steplen])
 
+    def is_leaf(self):
+        """:returns: True if the node is a leaf node (else, returns False)"""
+        return self.numchild == 0
+
     def get_ancestors(self):
         """
         :returns: A queryset containing the current node object's ancestors,
            node's new position
         """
 
-        pos = self._fix_move_opts(pos)
+        pos = self._prepare_pos_var_for_move(pos)
 
         oldpath = self.path
 

File treebeard/ns_tree.py

     def add_sibling(self, pos=None, **kwargs):
         """Adds a new node as a sibling to the current node object."""
 
-        pos = self._fix_add_sibling_opts(pos)
+        pos = self._prepare_pos_var_for_add_sibling(pos)
 
         # creating a new object
         newobj = self.__class__(**kwargs)
         relative to another node.
         """
 
-        pos = self._fix_move_opts(pos)
+        pos = self._prepare_pos_var_for_move(pos)
         cls = self.__class__
 
         parent = None
                 return self._cached_parent_obj
         except AttributeError:
             pass
-            # parent = our most direct ancestor
+        # parent = our most direct ancestor
         self._cached_parent_obj = self.get_ancestors().reverse()[0]
         return self._cached_parent_obj
 

File treebeard/templatetags/admin_tree.py

             result_repr = EMPTY_CHANGELIST_VALUE
         else:
             if f is None:
-                allow_tags = getattr(attr, 'allow_tags', False)
-                boolean = getattr(attr, 'boolean', False)
-                if boolean:
+                if getattr(attr, 'boolean', False):
                     allow_tags = True
                     result_repr = _boolean_icon(value)
                 else:
+                    allow_tags = getattr(attr, 'allow_tags', False)
                     result_repr = smart_str(value)
-                    # Strip HTML tags in the resulting text, except if the
-                # function has an "allow_tags" attribute set to True.
-                if not allow_tags:
+                if allow_tags:
+                    result_repr = mark_safe(result_repr)
+                else:
+                    # strip HTML tags
                     result_repr = escape(result_repr)
-                else:
-                    result_repr = mark_safe(result_repr)
             else:
                 if isinstance(f.rel, models.ManyToOneRel):
                     result_repr = escape(getattr(result, f.name))
                     row_class = ' class="nowrap"'
         if force_str(result_repr) == '':
             result_repr = mark_safe('&nbsp;')
-            # If list_display_links not defined, add the link tag to the
+        # If list_display_links not defined, add the link tag to the
         # first field
         if (
             (first and not cl.list_display_links) or