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.

Example

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

Install the django-simple-history library −

pip install django-simple-history

In settings.py

INSTALLED_APPS+=[" simple_history"]
MIDDLEWARE = [
   #other middle ware
   'simple_history.middleware.HistoryRequestMiddleware',
]

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

Here we don't have much to do on urls.py and views.py because our main work will be with models.py and admin.py.

In models.py, add the following −

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

# Create your models here.
class StudentData(models.Model):
   name=models.CharField(max_length=100)
   standard=models.CharField(max_length=100)
   section=models.CharField(max_length=100)
   history = HistoricalRecords()

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

In admin.py, add the following lines −

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

admin.site.register(StudentData,SimpleHistoryAdmin)

Here we registered the model with history tracking admin.

Now run these commands −

python manage.py makemigrations
python manage.py migrate
python manage.py createsuperuser

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

Output

You can query it in views.py or Django shell.

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