DEV Community

loading...
Cover image for Tracking Database Changes in Django

Tracking Database Changes in Django

Mohamed M El-Kalioby
A Developer with round 15 years experience
・1 min read

First, the credit of the cover photo is for https://matomo.org/

When working in mission-critical applications, it is critical to know when and how an object (DB row) got here.

For that, we created django-model-tracker a Django application that handle tracking Django Models changes with the username of the user who did the change, then the admin team can view the changes and restore the object to an older state.

Installation

  1. Install the package from pip pip install django-model-tracker
  2. In the settings.py add ModelTracker to INSTALLED_APPS.

    INSTALLED_APPS = (
     '....',
    'ModelTracker',
    '....'
    )
    
  3. Run the migrations for the application
    python manage.py migrate ModelTracker

Tracking your models

To track a model, you need to change the inheritance from models.Model to ModelTracker.Tracker e.g

from ModelTracker import Tracker
class Employee(Tracker.ModelTracker):
    name=models.CharField(max_length=255)
    ....
Enter fullscreen mode Exit fullscreen mode

When you save an Employee object, you can pass the username as follows

emp=Employee()
emp.save(request.user.username)
Enter fullscreen mode Exit fullscreen mode

Notes:

  1. If you don't pass a username, ModelTracker will check pick the username from a ModelTracker middleware (ModelTracker.middleware.ModelTrackerMiddleware)
  2. You can pass username as None to skip saving the tracking info.
  3. The username is a string so you can give names for the management commands as you like.
  4. There is second optional parameter which event_name which can be used a tag the change.

This is a quick tour for django-model-tracker, you can find more information on the GitHub Repo

Discussion (0)