Skip to main content

A library for writing reliable data invariants in Django.

Project description

Django Queryset Constraint

Build Status Release Status License Python Versions Django Versions

This library enables one to write reliable data invariants, by compiling Django Querysets to database insert/update triggers, via. the migration system.


Django has a built-in signal system, which emits signals on various events, for instance model creations, updates and deletions. However these signals are not emmited for queryset operations, and as such cannot be used to maintain data invariants.

An attempt to ratify this was made with the Django Queryset Signals library. While this library comes closer to a reliable solution, it does not succeed, as it is stil possible to break the data invariants by accessing the database directly.

Database Constraint Triggers will effectively protect against all scenarios.


pip install django_queryset_constraint


  • Add the django_queryset_constraint app to INSTALLED_APPS:

Note: This should be done before any apps that will be checked

  • Add QuerysetConstraint to constraints to the Meta class of the models to checked:
from django.db import models
from django.db.models import Count
from django_queryset_constraint import M, QuerysetConstraint

class Topping(models.Model):
    name = models.CharField(max_length=30)

class PizzaTopping(models.Model):
    class Meta:
        unique_together = ("pizza", "topping")
        constraints = [
            # A pizza with more than 5 toppings gets soggy
                name='At most 5 toppings',
            # This constraint should be self-explanatory for civilized people
                name='No pineapple',

    pizza = models.ForeignKey('Pizza', on_delete=models.CASCADE)
    topping = models.ForeignKey(Topping, on_delete=models.CASCADE)

class Pizza(models.Model):
    name = models.CharField(max_length=30)
    toppings = models.ManyToManyField(Topping, through=PizzaTopping)
  • Make migrations: python makemigrations
  • Run migrations: python migrate

Note: Complex triggers introduce performance overhead.

Support Matrix

This app supports the following combinations of Django and Python:

Django Python
2.2 3.6, 3.7

Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

django_queryset_constraint-1.0.6.tar.gz (14.3 kB view hashes)

Uploaded source

Supported by

AWS AWS Cloud computing Datadog Datadog Monitoring Facebook / Instagram Facebook / Instagram PSF Sponsor Fastly Fastly CDN Google Google Object Storage and Download Analytics Huawei Huawei PSF Sponsor Microsoft Microsoft PSF Sponsor NVIDIA NVIDIA PSF Sponsor Pingdom Pingdom Monitoring Salesforce Salesforce PSF Sponsor Sentry Sentry Error logging StatusPage StatusPage Status page