Skip to main content

Django Integrity

Django Integrity contains tools for controlling deferred constraints and handling IntegrityErrors in Django projects which use PostgreSQL.

Deferrable constraints

Some PostgreSQL constraints can be defined as DEFERRABLE. A constraint that is not deferred will be checked immediately after every command. A deferred constraint check will be postponed until the end of the transaction. A deferrable constraint will default to either DEFERRED or IMMEDIATE.

The utilities in django_integrity.constraints can ensure a deferred constraint is checked immediately, or defer an immediate constraint.

These alter the state of constraints until the end of the current transaction:

  • set_all_immediate(using=...)
  • set_immedate(names=(...), using=...)
  • set_deferred(names=(...), using=...)

To enforce a constraint immediately within some limited part of a transaction, use the immediate(names=(...), using=...) context manager.

Why do we need this?

This is most likely to be useful when you want to catch a foreign-key violation (i.e.: you have inserted a row which references different row which doesn't exist).

Django's foreign key constraints are deferred by default, so they would normally raise an error only at the end of a transaction. Using try to catch an IntegrityError from a foreign-key violation wouldn't work, and you'd need to wrap the COMMIT instead, which is trickier.

By making the constraint IMMEDIATE, the constraint would be checked on INSERT, and it would be much easier to catch.

More generally, if you have a custom deferrable constraint, it may be useful to change the default behaviour with these tools.

Refining IntegrityError

The refine_integrity_error context manager in django_integrity.conversion will convert an IntegrityError into a more specific exception based on a mapping of rules to your custom exceptions, and will raise the IntegrityError if it doesn't match.

Why do we need this?

When a database constraint is violated, we usually expect to see an IntegrityError.

Sometimes we need more information about the error: was it a unique constraint violation, or a check-constraint, or a not-null constraint? Perhaps we ran out of 32-bit integers for our ID column? Failing to be specific on these points could lead to bugs where we catch an exception without realising it was not the one we expected.

Example

from django_integrity import conversion
from users.models import User


class UserAlreadyExists(Exception): ...
class EmailCannotBeNull(Exception): ...
class EmailMustBeLowerCase(Exception): ...


def create_user(email: str) -> User:
    """
    Creates a user with the provided email address.

    Raises:
        UserAlreadyExists: If the email was not unique.
        EmailCannotBeNull: If the email was None.
        EmailMustBeLowerCase: If the email had a non-lowercase character.
    """
    rules = [
        (conversion.Unique(model=User, fields=("email",)), UserAlreadyExists),
        (conversion.NotNull(model=User, field="email"), EmailCannotBeNull),
        (conversion.Named(name="constraint_islowercase"), EmailMustBeLowerCase),
    ]
    with conversion.refine_integrity_error(rules):
        User.objects.create(email=email)

Supported dependencies

This package is tested against:

  • Python 3.10, 3.11, or 3.12.
  • Django 4.1, 4.2, or 5.0.
  • PostgreSQL 12 to 16.
  • psycopg2 and psycopg3.

Metadata

Release files for django-integrity 0.2.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for django-integrity 0.2.0
File Size Uploaded Provenance
django_integrity-0.2.0.tar.gz 10.9 kB Without provenance Details

Built distribution (wheel)

Table of built distributions (wheels) for django-integrity 0.2.0
File Interpreter ABI Platform
django_integrity-0.2.0-py3-none-any.whl Python 3 none any Details

Total release size: 20.2 kB

Release files / django_integrity-0.2.0.tar.gz

Download URL django_integrity-0.2.0.tar.gz
Size 10.9 kB
Tags Source
SHA-256 checksum
How to use checksums
6b7cd3779f7c06d3fbdfeb90f94bbf8b40d17a1c15b30362febab36506dc1cab
BLAKE2b-256 checksum
How to use checksums
154251158206450c032f5b6fbd00fe5d798b683062815c7de69df5261438b3c8
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/5.0.0 CPython/3.12.3

Release files / django_integrity-0.2.0-py3-none-any.whl

Download URL django_integrity-0.2.0-py3-none-any.whl
Size 9.2 kB
Tags Python 3
SHA-256 checksum
How to use checksums
95f5b3d41d81046c3075282dd6338d38a03c9f009b9fa17d6d49be371cf4d949
BLAKE2b-256 checksum
How to use checksums
f5575e16edf77b493ed8fdba9e03bb62fb2dea078695248dbf6f7600979f463c
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/5.0.0 CPython/3.12.3

Security for django-integrity 0.2.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page