Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Model object's history tracking in Django
Model history tracking in Django allows you to track changes made to model objects, including what changes were made, when they occurred, and helps in recovery of deleted objects. The django-simple-history package provides an easy way to implement this functionality.
Installation and Setup
First, install the django-simple-history library ?
pip install django-simple-history
Add the package to your Django settings in settings.py ?
INSTALLED_APPS = [
# other apps
'simple_history',
]
MIDDLEWARE = [
# other middleware
'simple_history.middleware.HistoryRequestMiddleware',
]
The middleware captures the user making changes and timestamps for historical records.
Creating a Model with History Tracking
In models.py, add the HistoricalRecords field to enable tracking ?
from django.db import models
from simple_history.models import HistoricalRecords
class StudentData(models.Model):
name = models.CharField(max_length=100)
standard = models.CharField(max_length=100)
section = models.CharField(max_length=100)
history = HistoricalRecords()
def __str__(self):
return self.name
The history field automatically tracks all create, update, and delete operations on this model.
Admin Configuration
Register the model with history tracking in admin.py ?
from django.contrib import admin from .models import StudentData from simple_history.admin import SimpleHistoryAdmin admin.site.register(StudentData, SimpleHistoryAdmin)
Run the database migrations to create the history table ?
python manage.py makemigrations python manage.py migrate python manage.py createsuperuser
Accessing Historical Data
You can query historical records programmatically in views or Django shell ?
# Get all historical records for a student
student = StudentData.objects.get(id=1)
history = student.history.all()
# Print historical changes
for record in history:
print(f"Changed on: {record.history_date}")
print(f"Change type: {record.history_type}")
print(f"Changed by: {record.history_user}")
print(f"Name: {record.name}")
print("---")
Key Features
| Feature | Description | Access Method |
|---|---|---|
| Change Tracking | Tracks create, update, delete | model.history.all() |
| User Tracking | Records who made changes | record.history_user |
| Timestamp | When changes occurred | record.history_date |
| Change Type | Created (+), Updated (~), Deleted (-) | record.history_type |
Conclusion
Django-simple-history provides comprehensive model history tracking with minimal setup. It automatically creates historical records for all model changes and integrates seamlessly with Django admin for easy management and recovery of data.
