Django Model Utils

5.0.0 · active · verified Thu Apr 09

Django Model Utils is a comprehensive Python library that provides a collection of abstract base classes, managers, fields, and utilities designed to simplify common Django model patterns. It includes features like `StatusField` for managing object states, `TimeStampedModel` for automatic creation/modification timestamps, `SoftDeletableModel` for logical deletion, and `FieldTracker` for monitoring field changes. The current version is 5.0.0, and it generally keeps pace with Django's major release cycle for compatibility.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to use `FieldTracker` to monitor changes in a model's fields. The `tracker` instance on the model allows you to check if a specific field has changed (`has_changed()`), retrieve its previous value (`previous()`), or get a dictionary of all changed fields and their old values (`changed()`). The example shows how to integrate this logic within a custom `save` method.

from django.db import models
from model_utils import FieldTracker

class Post(models.Model):
    title = models.CharField(max_length=100)
    body = models.TextField()
    tracker = FieldTracker()

    def save(self, *args, **kwargs):
        # Example of using FieldTracker in a save method
        super().save(*args, **kwargs)
        if self.tracker.has_changed('title'):
            print(f"Title changed from '{self.tracker.previous('title')}' to '{self.title}'")

# Example usage (requires Django setup and database interaction)
# post = Post.objects.create(title='Initial Title', body='Some body content')
# post.title = 'Updated Title'
# post.save()
# print(post.tracker.changed()) # Shows all changed fields and their previous values

view raw JSON →