How it works...

The MP_Node abstract model provides the path, depth, and numchild fields, as well as the steplenalphabet, and node_order_by attributes, to the Category model as necessary for constructing the tree:

  • The depth and numchild fields provide metadata about a node's location and descendants.
  • The path field is indexed, enabling database queries against it using LIKE to be very fast.
  • The path field is made up of fixed-length encoded segments, where the size of each segment is determined by the steplen attribute value (which defaults to 4), and the encoding uses characters found in the given alphabet attribute value (defaults to Latin alphanumeric characters).

The path, depth, and numchild fields should be treated as read-only. Also, steplen, alphabet, and node_order_by values should never be changed after saving the first object to a tree; otherwise, the data will be corrupted.

Besides new fields and attributes, the MP_Node abstract class adds methods for navigation through the tree structure. Some important examples of these methods are listed here:

  • If you want to get the ancestors of a category, which are returned as QuerySet of ancestors from the root to the parent of the current node, use the following code:
ancestor_categories = category.get_ancestors()
  • To just get the root category, which is identified by having a depth of 1, use the following code:
root = category.get_root()
  • If you want to get the direct children of a category, use the following code:
children = category.get_children()
  • To get all descendants of a category, returned as QuerySet of all children and their children, and so on, but not including the current node itself, use the following code:
descendants = category.get_descendants()
  • If you want to get just the descendant count, use the following code:
descendants_count = category.get_descendant_count()
  • To get all siblings, including the reference node, call the following method:
siblings = category.get_siblings()
Root categories are considered to be siblings of other root categories.
  • To just get the previous and next siblings, call the following methods, where get_prev_sibling() will return None for the leftmost sibling, as will get_next_sibling() for the rightmost one:
previous_sibling = category.get_prev_sibling()
next_sibling = category.get_next_sibling()
  • Also, there are methods to check whether the category is root, leaf, or related to another node:
category.is_root()
category.is_leaf()
category.is_child_of(another_category)
category.is_descendant_of(another_category)
category.is_sibling_of(another_category)
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.129.210.17