Django Modelcluster

6.4.1 · active · verified Thu Apr 09

django-modelcluster is a Django extension that allows working with 'clusters' of related models as a single unit, independently of the database. It introduces `ParentalKey` and `ClusterableModel` to enable in-memory manipulation of related objects, which is particularly useful for features like previews and revisions in content management systems like Wagtail. The current version is 6.4.1, and it maintains a consistent release schedule, often aligning with Django and Python version support.

Warnings

Install

Imports

Quickstart

This example demonstrates defining a `ClusterableModel` (Band) and a related model (`BandMember`) connected via `ParentalKey`. It shows how to create a cluster of related objects in memory and access them before saving them to the database.

from django.db import models
from modelcluster.models import ClusterableModel
from modelcluster.fields import ParentalKey

class Band(ClusterableModel):
    name = models.CharField(max_length=255)

    def __str__(self):
        return self.name

class BandMember(models.Model):
    band = ParentalKey(
        'Band', 
        related_name='members',
        on_delete=models.CASCADE
    )
    name = models.CharField(max_length=255)

    def __str__(self):
        return self.name

# Example usage (in a Django shell or view):
beatles = Band(name='The Beatles')
# Related objects can be assigned to the in-memory 'members' attribute
beatles.members = [
    BandMember(name='John Lennon'),
    BandMember(name='Paul McCartney'),
    BandMember(name='George Harrison'),
    BandMember(name='Ringo Starr'),
]

# Accessing in-memory members (behaves like a QuerySet subset)
print([member.name for member in beatles.members.all()])
# Output: ['John Lennon', 'Paul McCartney', 'George Harrison', 'Ringo Starr']

# To save the cluster and its members to the database:
# beatles.save()
# This would also save all associated BandMember instances via ParentalKey

view raw JSON →