django-pgtrigger

4.17.0 · active · verified Sun Apr 12

django-pgtrigger is a Python library that enables the creation and management of PostgreSQL triggers directly from Django models. It simplifies the process of integrating powerful database-level logic, such as protecting operations, enforcing read-only fields, or soft-deleting models, into Django applications. The library is actively maintained, frequently releasing new versions to support the latest Django, Python, and PostgreSQL releases.

Warnings

Install

Imports

Quickstart

To quickly get started, install `django-pgtrigger` and add `pgtrigger` to your `INSTALLED_APPS`. Define triggers directly in your Django model's `Meta.triggers` list using built-in trigger classes like `pgtrigger.Protect`. After defining, run `makemigrations` and `migrate` to install the triggers in your PostgreSQL database.

import pgtrigger
from django.db import models

class ProtectedModel(models.Model):
    name = models.CharField(max_length=100)

    class Meta:
        app_label = 'myapp'
        triggers = [
            pgtrigger.Protect(name="prevent_deletes", operation=pgtrigger.Delete)
        ]

# To see this in action, after adding 'pgtrigger' to INSTALLED_APPS and 'myapp' to your Django project:
# 1. python manage.py makemigrations
# 2. python manage.py migrate
# 3. From a Django shell:
#    from myapp.models import ProtectedModel
#    ProtectedModel.objects.create(name='Test')
#    ProtectedModel.objects.first().delete() # This will raise a ProgrammingError from PostgreSQL

view raw JSON →