DEV Community

Cover image for Tracking Database Changes in Django
Mohamed M El-Kalioby
Mohamed M El-Kalioby Subscriber

Posted on

3

Tracking Database Changes in Django

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

Heroku

This site is built on Heroku

Join the ranks of developers at Salesforce, Airbase, DEV, and more who deploy their mission critical applications on Heroku. Sign up today and launch your first app!

Get Started

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay