History tracking for Django and Postgres
Maintained. Last release 9 months ago, commits in 0 of the last 26 weeks. Weaker on commit activity.
pip install django-pghistorydjango-pghistory
django-pghistory tracks changes to your Django models using Postgres triggers, providing:
- Reliable history tracking everywhere with no changes to your application code.
- Structured history models that mirror the fields of your models.
- Grouping of history with additional context attached, such as the logged-in user.
django-pghistory has a number of ways in which you can configure history tracking for your application's needs and for performance and scale. An admin integration and middleware is included out of the box too.
Quick Start
Decorate your model with pghistory.track. For example:
import pghistory
@pghistory.track()
class TrackedModel(models.Model):
int_field = models.IntegerField()
text_field = models.TextField()
Above we've tracked TrackedModel. Copies of the model will be stored in a dynamically-created event model on every insert and update.
Run python manage.py makemigrations followed by migrate and voila, every change to TrackedModel is now stored. This includes bulk methods and even changes that happen in raw SQL. For example:
from myapp.models import TrackedModel
m = TrackedModel.objects.create(int_field=1, text_field="hello")
m.int_field = 2
m.save()
print(m.events.values("pgh_obj", "int_field"))
> [{'pgh_obj': 1, 'int_field': 1}, {'pgh_obj': 1, 'int_field': 2}]
Above we printed the history of int_field. We also printed pgh_obj, which references the tracked object. We'll cover how these fields and additional metadata fields are tracked later.
django-pghistory can track a subset of fields and conditionally store events based on specific field transitions. Users can also store free-form context from the application in event metadata, all with no additional database queries. See the next steps below on how to dive deeper and configure it for your use case.
Compatibility
django-pghistory is compatible with Python 3.10 - 3.14, Django 4.2 - 6.0, Psycopg 2 - 3, and Postgres 14 - 18.
Documentation
View the django-pghistory docs here to learn more about: