Package: django-tree
⚠ Open to financing MySQL & SQLite compatibility ⚠Fast and easy tree structures.In beta, it can’t be used yet in production.This tool works in a very similar way todjango-mpttanddjango-treebeard, however it’s so different in conception
that it was better and faster to start from scratch
than to rewrite the existing solutions.Compared to these solutions, django-tree aims to have these advantages
(some of them are already there):less intrusive (no more inheriting issues
due to Model, Manager & Queryset subclasses)easier to installeasier to usemore completeminimalist (less code, less database fields)bug-freesafe (most of the logic is written directly in database)faster for all operationsHowever, there is nothing groundbreaking here: this is only the result of
a proper use of the latest Django improvements, combined with a good knowledge
of SQL.BenchmarkThe detailed benchmarkgives a good idea
on how well django-tree performs compared to other Django solutions.
All that while being simpler to use, more robust and fully generalized to raw SQL, bulk etc.A few noteworthy extracts of the benchmark (less is better):InstallationDjango-tree requires Django 1.8, 1.11 or 2.0 and Python 2 or 3.
For the moment, django-tree is only for PostgreSQL.
It will be adapted in the future for other databases.After installing the module, you need to add'tree',to yourINSTALLED_APPS, then add aPathFieldto a model with aForeignKey('self'), typically namedparent(use theparent_fieldargument ofCreateTreeTriggerif the field has another name).PathFieldstoresPathobjects which have methods to execute queries,
such as getting all the descendants of the current object, its siblings, etc.
To call these methods more conveniently, you can addTreeModelMixinto your model.  The inheriting order is not important, as the mixin methods
do not clash with Django.  If you have multiplePathFieldon the same model, you will have to specify the field name in the method
you’re calling usingpath_field.This should give you a model like this:fromdjango.db.modelsimportModel,CharField,ForeignKey,BooleanFieldfromtree.fieldsimportPathFieldfromtree.modelsimportTreeModelMixinclassYourModel(Model,TreeModelMixin):name=CharField(max_length=30)parent=ForeignKey('self',null=True,blank=True)path=PathField()public=BooleanField(default=False)classMeta:ordering=['path']Then you need to create the SQL trigger that will automatically updatepath.
To do that, create a migration with a dependency
to the latest django-tree migration and add aCreateTreeTriggeroperation:fromdjango.dbimportmigrationsfromtree.operationsimportCreateTreeTriggerclassMigration(migrations.Migration):dependencies=[('tree','0001_initial'),]operations=[CreateTreeTrigger('your_app.YourModel'),]If you already have data inYourModel, you will need to add an operation
for allowing SQLNULLvalues before creating the trigger,
then rebuild the paths and revert the allowance ofNULLvalues:fromdjango.dbimportmigrationsfromtree.fieldsimportPathFieldfromtree.operationsimportCreateTreeTrigger,RebuildPathsclassMigration(migrations.Migration):dependencies=[('tree','0001_initial'),]operations=[migrations.AlterField('YourModel','path',PathField(null=True)),CreateTreeTrigger('YourModel'),RebuildPaths('YourModel','path'),migrations.AlterField('YourModel','path',PathField()),]However, the model above is not ordered. The children of a same parent will be
ordered by primary key. You can specify how children are ordered using theorder_byargument ofPathField. If needed, you can add a field
for users to explicitly order these objects, typically a position field.
Example model:fromdjango.db.modelsimport(Model,CharField,ForeignKey,IntegerField,BooleanField)fromtree.fieldsimportPathFieldfromtree.modelsimportTreeModelMixinclassYourModel(Model,TreeModelMixin):name=CharField(max_length=30)parent=ForeignKey('self',null=True,blank=True)position=IntegerField(default=1)path=PathField(order_by=['position','name'])public=BooleanField(default=False)classMeta:ordering=['path']And the corresponding migration:fromdjango.dbimportmodels,migrationsfromtree.operationsimportCreateTreeTriggerclassMigration(migrations.Migration):dependencies=[('tree','0001_initial'),]operations=[migrations.AddField('YourModel','position',models.IntegerField(default=1))CreateTreeTrigger('YourModel'),]Here, the children of a same parent will be ordered by position, and then
by name if the position is the same.NoteYou can also usePathFieldwithout adding aCreateTreeTriggeroperation. However, the field will not automatically be updated, you
will have to do it by yourself. In most cases this is not useful, so you
should not usePathFieldwithoutCreateTreeTriggerunless you know
what you are doing.UsagePathFieldis automatically filled thanks toCreateTreeTrigger,
you don’t need to set, modify, or even see its value once it is installed.
But you can use thePathobject it stores or the more convenientTreeModelMixinto get tree information about the current instance,
or make complex queries on the whole tree structure.
Example to show you most of the possibilities:obj=YourModel.objects.all()[0]obj.path.get_level()obj.get_level()# Shortcut for the previous method, if you use# `TreeModelMixin`. Same for other object methods below.obj.is_root()obj.is_leaf()obj.get_children()obj.get_children().filter(public=True)obj.get_ancestors()obj.get_ancestors(include_self=True)obj.get_descendants(include_self=True)obj.get_siblings()obj.get_prev_sibling()# Fetches the previous sibling.obj.get_next_sibling()# Same as `get_prev_sibling`, except that we get the first public one.obj.get_prev_siblings().filter(public=True).first()other=YourModel.objects.all()[1]obj.is_ancestor_of(other)obj.is_descendant_of(other,include_self=True)YourModel.objects.filter_roots()## Advanced usage# Use the following methods only if you understand exactly what they mean.#YourModel.rebuild_paths()# Rebuilds all paths of this field, useful only# if something is broken, which shouldn’t happen.YourModel.disable_tree_trigger()# Disables the SQL trigger.YourModel.enable_tree_trigger()# Restores the SQL trigger.withYourModel.disabled_tree_trigger():# What happens inside this context manager is ignored# by the SQL trigger.# The trigger is restored after that, even if there an error occurred.passThere is also a bunch of less useful lookups and transforms
available. They will be documented with examples in the future.Differences with MPTT and treebeardLevel vs depthdjango-mptt and django-treebeard use two different names to designate almost
the same thing: MPTT uses level and treebeard uses depth.
Both are integers to show how much distant is a node from the top of the tree.
The only difference is that level should start by convention with 1 and depth
should start with 0.Unfortunately,both MPTT and treebeard are wrong about the indexing:
MPTT starts its level with 0 and treebeard starts its depth with 1.Django-tree finally fixes this issue by implementing a level starting by 1,
and no depth to avoid confusion. One name had to be chosen, and I find that
“level” represents more accurately the idea that we deal with an abstract tree,
where all the node of the same level are on the same row.
In comparison, “depth” sounds like we’re actually digging a real root,
and it gives the impression that a child of a root
can be at a different depth than a child of another root, like in real life.