What is django-modelcluster and how does it work?
maindjango-modelcluster allows you to work with 'clusters' of related objects in memory before they are saved to the database. This is useful for scenarios like rendering data previews of unsaved forms, constructing trees for serialization, or handling draft states and revisions without complex database redesigns.
It achieves this by extending Django's foreign key relations. By using ClusterableModel on a parent model and ParentalKey on child models, related objects are stored locally to the parent in memory. These objects can be accessed via a subset of the QuerySet API (like .all(), .add(), and .count()) even before the parent is saved to the database.
from modelcluster.models import ClusterableModel
from modelcluster.fields import ParentalKey
class Band(ClusterableModel):
name = models.CharField(max_length=255)
class BandMember(models.Model):
band = ParentalKey('Band', related_name='members', on_delete=models.CASCADE)
name = models.CharField(max_length=255)
# Usage:
beatles = Band(name='The Beatles')
beatles.members = [
BandMember(name='John Lennon'),
BandMember(name='Paul McCartney'),
]
# The members exist in memory and can be queried:
# [member.name for member in beatles.members.all()] -> ['John Lennon', 'Paul McCartney']
beatles.save() # Only now are the records written to the database