Nested Sets trees

An implementation of Nested Sets trees for Django, as described by Joe Celko in Trees and Hierarchies in SQL for Smarties.

Nested sets have very efficient reads at the cost of high maintenance on write/delete operations.

Warning

As with all tree implementations, please be aware of the Known Caveats.

Inheritance diagram of NS_Node
class treebeard.ns_tree.NS_Node(*args, **kwargs)

Bases: Node

Abstract model to create your own Nested Sets Trees.

Warning

If you need to define your own Manager class, you’ll need to subclass NS_NodeManager.

Also, if in your manager you need to change the default queryset handler, you’ll need to subclass NS_NodeQuerySet.

node_order_by

Attribute: a list of model fields that will be used for node ordering. When enabled, all tree operations will assume this ordering.

Example:

node_order_by = ['field1', 'field2', 'field3']
depth

PositiveIntegerField, depth of a node in the tree. A root node has a depth of 1.

lft

PositiveIntegerField

rgt

PositiveIntegerField

tree_id

PositiveIntegerField

classmethod get_tree(parent=None)
Returns:

A queryset of nodes ordered as DFS, including the parent. If no parent is given, all trees are returned.

See: treebeard.models.Node.get_tree()

Note

This method returns a queryset.

class treebeard.ns_tree.NS_NodeManager(*args, **kwargs)

Bases: Manager

Custom manager for nodes in a Nested Sets tree.

class treebeard.ns_tree.NS_NodeQuerySet(model=None, query=None, using=None, hints=None)

Bases: QuerySet

Custom queryset for the tree node manager.

Needed only for the customized delete method.