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.
pip install django-dirtyfieldsVerified import paths — ran on the pinned version, not inferred.
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.
Be aware of this behavior when using Django 6.0+ and expressions. Review `get_dirty_fields()` output for fields that might be affected by Django's internal refresh mechanism.
After a transaction rollback, call `model.refresh_from_db()` on the instance to restore its correct state from the database. Alternatively, manually restore the in-memory fields that were edited.
Consider defining your base model without `DirtyFieldsMixin` and create a proxy model that inherits from both your base model and `DirtyFieldsMixin` for scenarios where dirty field tracking is necessary.
Account for signal execution when using `save_dirty_fields()`. If your signals rely on specific fields being dirty, ensure they are written to handle this, or consider alternative approaches if fine-grained signal control is needed.
After a transaction rollback, call `model.refresh_from_db()` on the model instance to synchronize its in-memory state with the database, or manually restore the edited fields.
Create a custom mixin that overrides the `_as_dict` method in `DirtyFieldsMixin` to specifically handle `File` or `ImageFieldFile` instances by converting their values to strings (e.g., the filename) before deepcopying.
To enable tracking for Foreign Key fields, pass the argument `check_relationship=True` to either the `is_dirty()` or `get_dirty_fields()` method.