django-tree-queries is a Django library that enables efficient querying of hierarchical data structures (trees) using adjacency lists and recursive Common Table Expressions (CTEs). It provides a lightweight solution for managing tree-like models within the Django ORM, focusing on explicit opt-in for tree-specific features rather than extensive configurability. The library is actively maintained, with version 0.24.0 currently available, supporting modern Django and Python versions.
pip install django-tree-queriesVerified import paths — ran on the pinned version, not inferred.
Define a model inheriting from `tree_queries.models.TreeNode`. This automatically adds a `parent` ForeignKey and provides tree-aware query methods. To access `tree_depth`, `tree_path`, and `tree_ordering` fields, you must explicitly call `.with_tree_fields()` on your queryset. Siblings can be ordered using `.order_siblings_by()` method.
Replace `.order_by(...)` with `.order_siblings_by('field_name')` for sibling ordering. General ordering of the full tree is implicit depth-first.Always append `.with_tree_fields()` to your queryset when you intend to access these tree-specific attributes. Example: `Category.objects.with_tree_fields().get(pk=1)`.
For very large datasets, consider using `tree_filter()` and `tree_exclude()` for better performance as they filter the base table before building the tree. For complex bottom-up aggregations, consider performing calculations in Python for small trees or exploring other tree libraries (e.g., django-treebeard, django-closuretree) if `django-tree-queries` becomes a bottleneck for specific use cases.
Ensure your model's self-referencing ForeignKey is defined as `parent = models.ForeignKey('self', ...)`Use the provided integer `tree_depth` and queryset methods for tree traversal and logic, avoiding direct parsing or reliance on the exact string format of `tree_path` or `tree_ordering` if your application needs to be future-proof or database-agnostic.
Design your tree structure to stay within the 50-level limit when using MySQL or MariaDB. Consider PostgreSQL for deeper trees.