Django Dirty Fields

1.9.9 · active · verified Mon Apr 13

django-dirtyfields is a small library for tracking 'dirty' fields on a Django model instance. A field is considered dirty if its in-memory value differs from the value currently saved in the database. The library is currently at version 1.9.9 and is actively maintained with regular updates to support new Django and Python versions.

Warnings

Install

Imports

Quickstart

To use django-dirtyfields, inherit from `DirtyFieldsMixin` in your Django model. Then, use `is_dirty()` to check if any fields have changed, or `get_dirty_fields()` to retrieve a dictionary of the original values for modified fields.

from django.db import models
from dirtyfields import DirtyFieldsMixin

class ExampleModel(DirtyFieldsMixin, models.Model):
    characters = models.CharField(max_length=80, default='initial value')
    boolean = models.BooleanField(default=True)

    def __str__(self):
        return self.characters

# Example Usage:
# Assuming an active Django environment and database
# model = ExampleModel.objects.create(characters='first value', boolean=True)
# print(f'Is dirty initially? {model.is_dirty()}') # Expected: False
# print(f'Dirty fields initially: {model.get_dirty_fields()}') # Expected: {}

# model.characters = 'second value'
# print(f'Is dirty after change? {model.is_dirty()}') # Expected: True
# print(f'Dirty fields after change: {model.get_dirty_fields()}') # Expected: {'characters': 'first value'}

# model.save()
# print(f'Is dirty after save? {model.is_dirty()}') # Expected: False
# model.boolean = False
# print(f'Is dirty after another change? {model.is_dirty()}') # Expected: True

view raw JSON →