How to Rebuild Django-MPTT Tree Structure
Most application utilize some sort of tree structure to managing data, in one form or another. One common use-case is nested categories.
If you are using Django for your current project and are in need to implement tree structures, there is a big change you have come across Django-MPTT.
Django-MPTT is a package for Django that includes utilities for implementing Modified Preorder Tree Traversal. The package is used throughout many other popular Django-based applications.
One concern to take into account when working with Modified Preorder Tree Traversal structures is the need to be able to rebuild the structure.
The tree can break, or simply you just want to re-order items in the tree.
For example, maybe you want to start structuring your tree ascending by title.
To do that with Django-MPTT you would need to add the following to the MPTTMETA.
#models.py
class MPTTMeta:
order_insertion_by = ['title']
After you save your models.py you can see that no change has taken affect. This is because you are working with a tree structure.
Without a rebuild of the tree, the previously added objects will not be accounted for and your tree will only be structured like this from now on.
To fix this you can rebuild your tree by using the rebuild command in the python shell.
#in python shell
ModelName.objects.rebuild()
Let's say you have a Category model that is an MPTTModel. To restructure it simply open up your command line interface and have your development environment activated (source bin/activate).
python manage.py shell
You will see that the shell is active by the three >>> visible. within the shell import the model that you want to rebuild the tree for. then run the build command.
from appname.models import Category
Category.objects.rebuild()
Simple as that, your tree has now been rebuilt.