Skip to content

An ltree extension implementation to support hierarchical tree-like data using the native Postgres extension ltree in django models

License

Notifications You must be signed in to change notification settings

mariocesar/django-ltree

Repository files navigation

django-ltree

A Django implementation for PostgreSQL's ltree extension, providing efficient storage and querying of hierarchical tree-like data.

See PostgreSQL's ltree documentation to learn more about it.

The main benefits of ltree:

  • Efficient path queries (ancestors, descendants, pattern matching)
  • Index-friendly hierarchical storage
  • Powerful label path searching
  • Native PostgreSQL performance for tree operations

Test PyPI Version

Features

  • Django model fields for ltree data types
  • Query utilities for common tree operations
  • Migration support for ltree extension installation
  • Compatibility with Django's ORM and query syntax

Requirements

  • Django 4.2+
  • Python 3.11+
  • PostgreSQL 14+ (with ltree extension enabled)

Installation

  1. Install the package:

    pip install django-ltree
  2. Add to your INSTALLED_APPS:

    INSTALLED_APPS = [
        ...
        "django_ltree",
        ...
    ]
  3. Run migrations to install the ltree extension:

    python manage.py migrate django_ltree
  4. Alternatively you can avoid install the application, and create the the extensions with a custom migration in an app in your project.

    from django.db import migrations
    from django_ltree.operations import LtreeExtension
    
    class Migration(migrations.Migration):
        initial = True
        dependencies = []
    
        operations = [LtreeExtension()]

Quick Start

  1. Add a PathField to your model:

    from django_ltree.fields import PathField
    
    class Category(models.Model):
        name = models.CharField(max_length=50)
        path = PathField()
  2. Create tree nodes:

    root = Category.objects.create(name="Root", path="root")
    child = Category.objects.create(name="Child", path=f"{root.path}.child")
  3. Query ancestors and descendants:

    # Get all ancestors
    Category.objects.filter(path__ancestor=child.path)
    
    # Get all descendants
    Category.objects.filter(path__descendant=root.path)

Migration Dependency

Include django_ltree as a dependency in your app's migrations:

class Migration(migrations.Migration):
    dependencies = [
        ("django_ltree", "__latest__"),
    ]

Documentation

For complete documentation, see [TODO: Add Documentation Link].

Links

Contributing

Contributions are welcome! Please see CONTRIBUTING.md for guidelines.

License

MIT License

About

An ltree extension implementation to support hierarchical tree-like data using the native Postgres extension ltree in django models

Topics

Resources

License

Stars

Watchers

Forks

Packages

No packages published