In your model you will have a foreign key pointing to the parent element of each element and a character field that will be used to store the structure (called "cache_hierarchy" in my code). Then add a _pre_commit handler like this: