Django Tree Queries

0.24.0 · active · verified Thu Apr 16

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.

Common errors

Warnings

Install

Imports

Quickstart

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.

import os
from django.db import models

# Assuming 'myapp' is in INSTALLED_APPS
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myproject.settings')
import django
django.setup()

from tree_queries.models import TreeNode

class Category(TreeNode):
    name = models.CharField(max_length=255)

    class Meta:
        app_label = 'myapp'

    def __str__(self):
        return self.name

# Example Usage (after makemigrations and migrate)
# from myapp.models import Category
# root = Category.objects.create(name='Electronics')
# child1 = Category.objects.create(name='Smartphones', parent=root)
# child2 = Category.objects.create(name='Laptops', parent=root)
# grandchild = Category.objects.create(name='Gaming Laptops', parent=child2)

# Retrieve a tree with additional fields
# for node in Category.objects.with_tree_fields().order_siblings_by('name'):
#     print(f"{'--' * node.tree_depth} {node.name} (depth: {node.tree_depth})")

view raw JSON →