Efficient tree-based datastructure for Django
Project description
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:
Node.objects.get(name='A').children.all()
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)
Node.objects.get(name='A').get_descendants()
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:
Node.rebuildtable()
Contributing
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 | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distributions
Hashes for django-closuretree-1.1.11.tar.gz
Algorithm | Hash digest | |
---|---|---|
SHA256 | 2b5d6ffc5d9610b59ea609687717cdc3225a40b2f807305251d67486e9ef1f30 |
|
MD5 | fce237b4ff07079bee8280e837b2d0ef |
|
BLAKE2b-256 | 7d10a9d27b2eada1ac488bda3fc4a7d34ae64b3e5fda7fc0da27ab489b990fa4 |
Hashes for django_closuretree-1.1.11-py3-none-any.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | 466e1b2ab21da9677eb7d958ced5783b43391bd1b4ab49c3c8862d570a9faf55 |
|
MD5 | d8ec79bd7fb7a8d51250f9749887507e |
|
BLAKE2b-256 | 062df7a89e75e8a13dc0d787264d4e211230c75059369f636c214e64856e0fc3 |
Hashes for django_closuretree-1.1.11-py2-none-any.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | 8040026bb4719edfe1f6218a25a15ca2df08e3085e07526cacee947fa4617e32 |
|
MD5 | ba3bd5097c85d5dd4f84052347b4c7a9 |
|
BLAKE2b-256 | 49330fcaacd82e204dcf3081fce31d73e2a83dd7507e1963df2965d7c70e7273 |