Django Treebeard

5.0.5 · active · verified Thu Apr 09

django-treebeard is a Django library providing efficient implementations for tree structures using Materialized Path (MPTT), Adjacency List, and Nested Sets algorithms. It offers a robust way to manage hierarchical data directly within Django models. The current stable version is 5.0.5, with releases typically aligning with Django's major versions to maintain compatibility and introduce new features.

Warnings

Install

Imports

Quickstart

Defines a basic `Category` model using `MP_Node` (Materialized Path) and demonstrates how to initialize the tree and add nodes. Remember to run `makemigrations` and `migrate` after defining your model. `node_order_by` is critical for consistent tree ordering.

from django.db import models
from treebeard.mp_tree import MP_Node

# Define a simple tree model inheriting from MP_Node (Materialized Path)
# This is generally the recommended tree type for most use cases.
class Category(MP_Node):
    name = models.CharField(max_length=255)

    # Crucial for deterministic ordering of siblings
    node_order_by = ['name']

    class Meta:
        verbose_name_plural = 'categories'

    def __str__(self):
        return self.name

# Example usage (e.g., in a Django shell or view):
# Create root nodes
# root1 = Category.add_root(name='Electronics')
# root2 = Category.add_root(name='Books')

# Add children to root1
# phone = root1.add_child(name='Phones')
# laptop = root1.add_child(name='Laptops')

# Add a grandchild to phone
# iphone = phone.add_child(name='iPhones')

# Retrieve and traverse
# for node in Category.get_tree():
#     print(f"{'--' * node.depth} {node.name}")

view raw JSON →