Skip to main content

Efficient tree-based datastructure for Django

Project description

Build Status Code Health Badge Documentation Status Test Coverage Version Badge License Badge

django-closuretree is an implementation of the closure tree technique for Django applications designed to provide efficient querying of tree-based structures in a relational database. Its goal is to reduce the number of queries required when querying the children or parents of a given object.

Given the following model:

class Node(models.Model):
    name = models.CharField(max_length=24)
    parent = models.ForeignKey('self', related_name='children')

The children of each model can be queried with:


However, for recursive lookups, this results in a large number of queries. Instead, django-closuretree allows you to extract them all in one go:

from closuretree.models import ClosureModel

class Node(ClosureModel):
    name = models.CharField(max_length=24)
    parent = models.ForeignKey('self', related_name='children', null=True)

a = Node.objects.create(name='A')
Node.objects.create(name='B', parent=a)


A single query will obtain all the descendants.

Quick Start

  • Install django-closuretree with pip install django-closuretree.
  • Inherit your models from closuretree.models.ClosureModel instead of django.db.models.Model.

That’s it. You can now use get_descendants() and get_ancestors() on a model instance.

If you’re adding this to an existing application that already has data in the database, you’ll need to run the rebuildtable() method of each model before the closure tree will be populated with the existing data:



To contribute, fork the repo, do your work, and issue a pull request. We ask that contributors adhere to PEP8 standards, and include full tests for all their code.

Project details

Release history Release notifications

This version
History Node


History Node


History Node


History Node


History Node


History Node


History Node


History Node


History Node


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Filename, size & hash SHA256 hash help File type Python version Upload date
django_closuretree-1.2.0-py2-none-any.whl (12.0 kB) Copy SHA256 hash SHA256 Wheel py2 Nov 6, 2017
django_closuretree-1.2.0-py3-none-any.whl (12.0 kB) Copy SHA256 hash SHA256 Wheel py3 Nov 6, 2017
django-closuretree-1.2.0.tar.gz (12.7 kB) Copy SHA256 hash SHA256 Source None Nov 6, 2017

Supported by

Elastic Elastic Search Pingdom Pingdom Monitoring Google Google BigQuery Sentry Sentry Error logging CloudAMQP CloudAMQP RabbitMQ AWS AWS Cloud computing DataDog DataDog Monitoring Fastly Fastly CDN DigiCert DigiCert EV certificate StatusPage StatusPage Status page