Reusable Django app that stores hierarchical model data using MPTT fields for fast reads. Adds tree managers, model helpers, forms, templates, and admin tools.
Overview
django-mptt implements Modified Preorder Tree Traversal for Django models that need parent-child hierarchies. The approach precomputes left, right, level, and tree identifiers on each row so ancestry and descendant queries stay efficient at read time.
Registering a model adds the needed tree columns automatically and keeps structure consistent on create, delete, and parent changes. Levels can sort by configurable fields. Instance methods cover ancestors, siblings, descendants, repositioning, and related tree operations.
A TreeManager supports moving nodes, inserting anywhere in a tree, switching trees, and rebuild when bulk updates happen outside the app. Form fields, utility helpers, template tags, and admin classes help render and edit trees in standard Django UIs.
Writes and moves update many rows, so concurrent writes, bulk SQL, and external database changes can corrupt stored tree metadata; rebuild can recover but rewrites all rows. The maintainers note the package is kept on a best-effort basis with compatibility fixes but no new features, and suggest recursive CTE alternatives such as django-tree-queries for new designs where appropriate.
Key features
- Automatic MPTT model registration
- Tree structure maintenance on saves
- Ancestor and descendant queries
- TreeManager move and insert
- rebuild for bulk repair
- Tree form fields
- Template tags for trees
- Admin tree visualization
Use cases
- Category hierarchies
- Nested comment threads
- Organizational charts in Django
- Menu or taxonomy models