Model object's history tracking in Django

PythonServer Side ProgrammingProgramming

Model history tracking is a feature which tracks the changes in model object, it tracks things like what change you made in it and when you deleted it. It also helps in the recovery of deleted object of model. In this article, we will take an example to see how to track a model object's history in Django.


First of all, set up your project, apps, urls and a model.

Install the django-simple-history library −

pip install django-simple-history


INSTALLED_APPS+=[" simple_history"]
   #other middle ware

Here we added the "simple_history" module as app and a middleware.

Here we don't have much to do on and because our main work will be with and

In, add the following −

from django.db import models
from simple_history.models import HistoricalRecords

# Create your models here.
class StudentData(models.Model):
   history = HistoricalRecords()

Here we simply created a model and the history field that will save every change.

In, add the following lines −

from django.contrib import admin
from .models import StudentData
from simple_history.admin import SimpleHistoryAdmin,SimpleHistoryAdmin)

Here we registered the model with history tracking admin.

Now run these commands −

python makemigrations
python migrate
python createsuperuser

Now you are all set. The above codes in will save all the historical data in a field which you can access in or Django shell.


You can query it in or Django shell.

Published on 26-Aug-2021 13:05:03