Django PG History

3.9.2 · active · verified Wed Apr 15

django-pghistory is a Django library that provides simple, powerful, and performant history tracking for Django models using PostgreSQL's event triggers. It leverages database-level features for efficiency, making it suitable for auditing and versioning. The current stable version is 3.9.2, and it maintains a regular release cadence with several minor versions and patches throughout the year.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to define a Django model and enable history tracking using the `@pghistory.track` decorator. It also shows how to retrieve the historical events through the automatically generated history model. Remember to add `pghistory` and `pghistory.admin` to `INSTALLED_APPS` and run `makemigrations` and `migrate` after defining your models.

import os
import django
from django.conf import settings
from django.db import models

settings.configure(
    DEBUG=True,
    INSTALLED_APPS=[
        'django.contrib.auth',
        'django.contrib.contenttypes',
        'django.contrib.sessions',
        'django.contrib.sites',
        'django.contrib.messages',
        'django.contrib.staticfiles',
        'pghistory',
        'pghistory.admin',
        'your_app_name' # Replace with your actual app name
    ],
    DATABASES={
        'default': {
            'ENGINE': 'django.db.backends.postgresql',
            'NAME': os.environ.get('PG_DB_NAME', 'test_db'),
            'USER': os.environ.get('PG_DB_USER', 'test_user'),
            'HOST': os.environ.get('PG_DB_HOST', 'localhost'),
            'PORT': os.environ.get('PG_DB_PORT', '5432'),
            'PASSWORD': os.environ.get('PG_DB_PASSWORD', 'password'),
        }
    },
    MIDDLEWARE_CLASSES=(
        'django.contrib.sessions.middleware.SessionMiddleware',
        'django.middleware.common.CommonMiddleware',
        'django.middleware.csrf.CsrfViewMiddleware',
        'django.contrib.auth.middleware.AuthenticationMiddleware',
        'django.contrib.messages.middleware.MessageMiddleware',
    ),
    TEMPLATES=[
        {
            'BACKEND': 'django.template.backends.django.DjangoTemplates',
            'DIRS': [],
            'APP_DIRS': True,
            'OPTIONS': {
                'context_processors': [
                    'django.template.context_processors.debug',
                    'django.template.context_processors.request',
                    'django.contrib.auth.context_processors.auth',
                    'django.contrib.messages.context_processors.messages',
                ],
            },
        },
    ],
    STATIC_URL = '/static/',
    SECRET_KEY = 'a-very-secret-key',
)
django.setup()

import pghistory

# Define your model
@pghistory.track(fields=['name', 'value'])
class MyModel(models.Model):
    name = models.CharField(max_length=255)
    value = models.IntegerField(default=0)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    def __str__(self):
        return f"{self.name} - {self.value}"

    class Meta:
        app_label = 'your_app_name'

# After running makemigrations and migrate:
# from your_app_name.models import MyModel
# obj = MyModel.objects.create(name='Test', value=10)
# obj.value = 20
# obj.save()
#
# HistoryModel = pghistory.get_event_model(MyModel)
# for event in HistoryModel.objects.all():
#     print(f"ID: {event.pgh_obj_id}, Name: {event.name}, Value: {event.value}, Changed at: {event.pgh_created_at}")

view raw JSON →