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.
pip install django-treebeardVerified import paths — ran on the pinned version, not inferred.
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.
Upgrade your Python environment to 3.10+ and Django to 4.2+ before upgrading `django-treebeard` to version 5.x.
Always include `node_order_by = ['your_field_name']` in your tree model definition, specifying the fields by which sibling nodes should be ordered.
For most use cases, especially those requiring frequent traversal or large trees, prefer `MP_Node` (Materialized Path) or `NS_Node` (Nested Sets) over `AL_Node`.
After creating the model, run `makemigrations`, then manually run the `fix_tree` management command (`python manage.py fix_tree your_app_name.YourTreeModel`) to initialize the tree fields for existing data.