Skip to main content

Clade

A Django module for managing hierarchical data models through a tree of nodes, with kinship relationship queries and optional database-native optimisations.

pipeline status coverage PyPI License


Status

Pre-alphav0.4.0 published. API not yet stable.

Version Status Content
v0.4.0 ✅ Current Extended kinship (pibling, nibling, cousin — symmetric degree)
v0.5.0 🔄 Next Affinity model & storage decision (DD-005)

See the milestones and open issues on GitLab for the full roadmap.


What it does

Clade provides a Django application for modelling and querying tree-structured data. It exposes the full set of kinship relationships derivable from a node tree — not only parent/child pairs, but ancestors, descendants, siblings, and collateral lines (piblings, niblings, cousins…) — using gender-neutral terminology throughout.

It also introduces Affinity: a lateral relationship between nodes that share attribute values without any hierarchical link between them — inter-model by design, declared via Meta.affinity_rules (v0.5.0).

The module targets multiple database backends:

  • PostgreSQL with ltree — native optimisation (v0.3.0)
  • SQLite / other — pure-Django Materialized Path fallback (current)

Install

pip install django-clade
# settings.py
INSTALLED_APPS = [
    ...
    "clade",
]

Usage

from clade.models import CladeNode
from django.db import models


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


# Build a tree
root  = Category.objects.create(name="Root")
child = Category.objects.create(name="Child", parent=root)
leaf  = Category.objects.create(name="Leaf",  parent=child)

# Traverse
leaf.ancestors()             # QuerySet → [root, child]  (ordered by path)
root.descendants()           # QuerySet → [child, leaf]
child.siblings()             # QuerySet → []

leaf.is_root                 # False
leaf.is_leaf                 # True
leaf.root                    # → root

# Manager API
Category.objects.ancestors_of(leaf)
Category.objects.descendants_of(root)

# Deletion strategies
from clade.deletion import ADOPT

class Department(CladeNode):
    name = models.CharField(max_length=255)
    parent = models.ForeignKey(
        "self", null=True, blank=True,
        on_delete=ADOPT,          # re-parents children on delete
        related_name="children",
    )

# Extended kinship (v0.4.0) — pibling, nibling, cousin
grandparent = Category.objects.create(name="Grandparent")
parent      = Category.objects.create(name="Parent", parent=grandparent)
aunt        = Category.objects.create(name="Aunt",   parent=grandparent)
me          = Category.objects.create(name="Me",     parent=parent)
cousin      = Category.objects.create(name="Cousin", parent=aunt)

me.piblings()                 # QuerySet → [aunt]      (siblings of my parent)
aunt.niblings()               # QuerySet → [me]        (children of my siblings)
me.cousins()                  # QuerySet → [cousin]    (degree=2, the default)

# Manager API
Category.objects.piblings_of(me)
Category.objects.cousins_of(me, degree=2)

cousins()/cousins_of() use a symmetric degree, not the genealogical (degree, removed) convention: degree=2 (the default) matches "1st cousin"; degree=3 matches "2nd cousin". Candidates at a different depth than the node itself (genealogically "once removed", etc.) are not covered — see issue #56 for the full rationale and the planned post-v1.0.0 extension.


Affinity (v0.5.0)

Affinity models a non-hierarchical relationship: two nodes that share an attribute value, with no parent/child link between them. It's inter-model by design — a Department and a Project can be in Affinity even though they're unrelated concrete models, as long as both inherit CladeNode.

from django.db import models
from clade.affinity import AffinityRule
from clade.models import CladeNode


class Department(CladeNode):
    name    = models.CharField(max_length=255)
    region  = models.CharField(max_length=255, null=True, blank=True)
    manager = models.CharField(max_length=255, null=True, blank=True)

    class Meta(CladeNode.Meta):
        affinity_rules = [
            AffinityRule("region",  to="myapp.Project", target_field="cost_center", channel="geo"),
            AffinityRule("manager", to="myapp.Project", target_field="lead",         channel="management"),
        ]


class Project(CladeNode):
    title       = models.CharField(max_length=255)
    cost_center = models.CharField(max_length=255, null=True, blank=True)
    lead        = models.CharField(max_length=255, null=True, blank=True)


# Affinity rows are materialised automatically on save — no manual sync.
paris_dept = Department.objects.create(name="Paris office", region="paris", manager="alice")
paris_proj = Project.objects.create(title="Metro extension", cost_center="paris", lead="alice")

paris_dept.affinities(channel="geo")         # QuerySet[Project] → [paris_proj]
paris_dept.affinities(channel="management")  # QuerySet[Project] → [paris_proj]

# Works from either side — a passive target model (Project here) never
# itself declares affinity_rules, but still resyncs on its own save.
paris_proj.affinities(channel="geo")         # QuerySet[Department] → [paris_dept]

affinities(channel=None) returns a single QuerySet and raises HeterogeneousAffinityError if the result would span more than one partner model — this can happen when two different source models reuse the same channel name toward the same target (channel uniqueness is per declaring model, not global). Use affinities_grouped() for that case: it never raises, returning {model: QuerySet} instead of a single QuerySet.

paris_dept.affinities_grouped(channel="geo")
# {Project: <QuerySet [paris_proj]>}

Constraints:

  • local_field/target_field must be one of a fixed allowlist of scalar field types (CharField, IntegerField, DateField, BooleanField, and similar) — checked at manage.py check / CI startup (clade.E002). ManyToManyField, FileField, JSONField, FloatField, and ForeignKey/OneToOneField are rejected.
  • channel must be unique within a single model's affinity_rules list (clade.E001) — but is freely reusable across different source models.
  • Multi-hop transitive closure (AB and BC ⟹ A~C through an intermediate node neither A nor B declares a rule toward) is not computed in v0.5.0 — deferred to v0.6.0. Only the direct relationships an AffinityRule explicitly names are materialised.

See issue #5 (DD-005) for the full design rationale.


Requirements

  • Python 3.10+
  • Django 5.2+

Contributing

See CONTRIBUTING.md and CODE_OF_CONDUCT.md.


Licence

Apache License 2.0 — see LICENSE.txt and NOTICE.

Download files

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

Source Distribution

django_clade-0.5.0.tar.gz (85.8 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

django_clade-0.5.0-py3-none-any.whl (37.1 kB view details)

Uploaded Python 3

File details

Details for the file django_clade-0.5.0.tar.gz.

File metadata

  • Download URL: django_clade-0.5.0.tar.gz
  • Upload date:
  • Size: 85.8 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: uv/0.12.5 {"installer":{"name":"uv","version":"0.12.5","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Debian GNU/Linux","version":"13","id":"trixie","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

File hashes

Hashes for django_clade-0.5.0.tar.gz
Algorithm Hash digest
SHA256 22a50f5808a67bf99c76389475f4cdaddae57b8c7cbb6a2f0fac72b39aa9ee32
MD5 bc9577cf98feaa56c58ceef458a5a4f2
BLAKE2b-256 2357e882494a58a6d31f80a8b542a3d2e293e29bfa8114e4ce9c211169c1994b

See more details on using hashes here.

File details

Details for the file django_clade-0.5.0-py3-none-any.whl.

File metadata

  • Download URL: django_clade-0.5.0-py3-none-any.whl
  • Upload date:
  • Size: 37.1 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: uv/0.12.5 {"installer":{"name":"uv","version":"0.12.5","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Debian GNU/Linux","version":"13","id":"trixie","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

File hashes

Hashes for django_clade-0.5.0-py3-none-any.whl
Algorithm Hash digest
SHA256 b7ab1d1d086f946bd6f19724f135a3db7c71dfb632a67c4c42a0eb8c012a03ac
MD5 cfa4f3654bb49112622edde070bfc374
BLAKE2b-256 c1ea45284991545123adce547740d724ac7fa6b6af3c268f966da059230a177f

See more details on using hashes here.

Release history Release notifications | RSS feed

0.6.0

2 files

This release

0.5.0 This release

2 files

0.4.0

2 files

0.3.0

2 files

0.0.5.post1

2 files

0.0.5

2 files

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page