Package: django-tree-queries
Query Django model trees using adjacency lists and recursive common
table expressions. Supports PostgreSQL, sqlite3 (3.8.3 or higher) and
MariaDB (10.2.2 or higher) and MySQL (8.0 or higher, if running withoutONLY_FULL_GROUP_BY).Supports Django 2.2 or better, Python 3.6 or better. See the GitHub actions
build for more details.Features and limitationsSupports only integer and UUID primary keys (for now).Allows specifying ordering among siblings.Uses the correct definition of depth, where root nodes have a depth of
zero.The parent foreign key must be named"parent"at the moment (but
why would you want to name it differently?)The fields added by the common table expression always aretree_depth,tree_pathandtree_ordering. The names cannot
be changed.tree_depthis an integer,tree_pathan array of
primary keys andtree_orderingan array of values used for
ordering nodes within their siblings.Besides adding the fields mentioned above the package only adds queryset
methods for ordering siblings and filtering ancestors and descendants. Other
features may be useful, but will not be added to the package just because
it’s possible to do so.Little code, and relatively simple when compared to other tree
management solutions for Django. No redundant values so the only way
to end up with corrupt data is by introducing a loop in the tree
structure (making it a graph). TheTreeNodeabstract model class
has some protection against this.Supports only trees with max. 50 levels on MySQL/MariaDB, since those
databases do not support arrays and require us to provide a maximum
length for thetree_pathandtree_orderingupfront.Here’s a blog post offering some additional insight (hopefully) into the
reasons fordjango-tree-queries’ existence.UsageInstalldjango-tree-queriesusing pip.Extendtree_queries.models.TreeNodeor build your own queryset
and/or manager usingtree_queries.query.TreeQuerySet. TheTreeNodeabstract model already contains aparentforeign key
for your convenience and also uses model validation to protect against
loops.Call thewith_tree_fields()queryset method if you require the
additional fields respectively the CTE.Call theorder_siblings_by("field_name")queryset method if you want to
order tree siblings by a specific model field. Note that Django’s standardorder_by()method isn’t supported – nodes are returned according to thedepth-first search algorithm. It’s not possible to
order siblings by more than one field either.Create a manager usingTreeQuerySet.as_manager(with_tree_fields=True)if you want to add
tree fields to queries by default.Until documentation is more complete I’ll have to refer you to thetest suitefor additional instructions and usage examples, or check the recipes below.RecipesBasic modelsThe following two examples both extend theTreeNodewhich offers a few
agreeable utilities and a model validation method that prevents loops in the
tree structure. The common table expression could be hardened against such
loops but this would involve a performance hit which we don’t want – this is a
documented limitation (non-goal) of the library after all.Basic tree nodefromtree_queries.modelsimportTreeNodeclassNode(TreeNode):name=models.CharField(max_length=100)Tree node with ordering among siblingsNodes with the same parent may be ordered among themselves. The default is to
order siblings by their primary key but that’s not always very useful.fromtree_queries.modelsimportTreeNodeclassNode(TreeNode):name=models.CharField(max_length=100)position=models.PositiveIntegerField(default=0)classMeta:ordering=["position"]Add custom methods to querysetfromtree_queries.modelsimportTreeNodefromtree_queries.queryimportTreeQuerySetclassNodeQuerySet(TreeQuerySet):defactive(self):returnself.filter(is_active=True)classNode(TreeNode):is_active=models.BooleanField(default=True)objects=NodeQuerySet.as_manager()Querying the treeAll examples assume theNodeclass from above.Basic usage# Basic usage, disregards the tree structure completely.nodes=Node.objects.all()# Fetch nodes in depth-first search order. All nodes will have the# tree_path, tree_ordering and tree_depth attributes.nodes=Node.objects.with_tree_fields()# Fetch any node.node=Node.objects.order_by("?").first()# Fetch direct children and include tree fields. (The parent ForeignKey# specifies related_name="children")children=node.children.with_tree_fields()# Fetch all ancestors starting from the root.ancestors=node.ancestors()# Fetch all ancestors including self, starting from the root.ancestors_including_self=node.ancestors(include_self=True)# Fetch all ancestors starting with the node itself.ancestry=node.ancestors(include_self=True).reverse()# Fetch all descendants in depth-first search order, including self.descendants=node.descendants(include_self=True)# Temporarily override the ordering by siblings.nodes=Node.objects.order_siblings_by("id")Breadth-first searchNobody wants breadth-first search but if you still want it you can achieve it
as follows:nodes=Node.objects.with_tree_fields().extra(order_by=["__tree.tree_depth","__tree.tree_ordering"])Filter by depthIf you only want nodes from the top two levels:nodes=Node.objects.with_tree_fields().extra(where=["__tree.tree_depth <=%s"],params=[1],)Form fieldsdjango-tree-queries ships a model field and some form fields which augment the
default foreign key field and the choice fields with a version where the tree
structure is visualized using dashes etc. Those fields aretree_queries.fields.TreeNodeForeignKey,tree_queries.forms.TreeNodeChoiceField,tree_queries.forms.TreeNodeMultipleChoiceField.