django-pgtrigger provides primitives for configuring
Postgres triggers <https://www.postgresql.org/docs/current/sql-createtrigger.html>__
on Django models.
Triggers can solve a wide variety of database-level problems more elegantly and reliably than in the application-level of Django. Here are some common problems that can be solved with triggers, many of which we later show how to solve in the docs:
django-pghistory <https://django-pghistory.readthedocs.io>__ uses
django-pgtriggerto do this).
pip install django-pgtrigger and
Models are decorated with
@pgtrigger.register and supplied with
pgtrigger.Trigger objects. If you don't have access to the model definition,
you can still call
Users declare the plpgsql code manually
pgtrigger.Trigger object or can use the derived triggers in
django-pgtrigger that implement common scenarios. For example,
pgtrigger.Protect can protect operations on a model, such as deletions:
.. code-block:: python
from django.db import models import pgtrigger pgtrigger.Protect( name='protect_deletes', operation=pgtrigger.Delete ) ) class CannotBeDeletedModel(models.Model): """This model cannot be deleted!"""
django-pgtrigger aims to alleviate the boilerplate of triggers and
having to write raw SQL by using common Django idioms. For example, users
pgtrigger.F objects to
conditionally execute triggers based on the
being modified. For example, let's only protect deletes
against "active" rows of a model:
.. code-block:: python
from django.db import models import pgtrigger pgtrigger.Protect( name='conditional_deletion_protection', operation=pgtrigger.Delete, # Protect deletes when the OLD row of the trigger is still active condition=pgtrigger.Q(old__is_active=True) ) ) class CannotBeDeletedModel(models.Model): """Active model object cannot be deleted!""" is_active = models.BooleanField(default=True)
pgtrigger.F, and derived
objects can solve a wide array of Django problems without ever having to
write raw SQL. Users, however, can still customize
triggers and write as much raw SQL as needed for their use case.
For a complete run-through of
django-pgtrigger and all derived
triggers (along with a trigger cookbook!), read the
pgtrigger docs <https://django-pgtrigger.readthedocs.io/>__. The docs
have a full tutorial of how to configure triggers and lots of code examples.
After you have gone through the
tutorial in the docs, check out
is an interactive tutorial written for a Django meetup talk about
View the django-pgtrigger docs here <https://django-pgtrigger.readthedocs.io/>_.
Install django-pgtrigger with::
pip3 install django-pgtrigger
After this, add
pgtrigger to the
setting of your Django project.
For information on setting up django-pgtrigger for development and
contributing changes, view