A context manager/decorator which extends Django's atomic function with the ability to set isolation level and retries for a given transaction.
Low maintenance activity. Last release 12 months ago, commits in 0 of the last 26 weeks. Weaker on commit activity and release cadence.
pip install django-pgtransactiondjango-pgtransaction
django-pgtransaction offers a drop-in replacement for the default django.db.transaction module which, when used on top of a PostgreSQL database, extends the functionality of that module with Postgres-specific features.
At present, django-pgtransaction offers an extension of the django.db.transaction.atomic context manager/decorator which allows one to dynamically set transaction characteristics including:
- Isolation level
- Read mode (READ WRITE/READ ONLY)
- Deferrability (DEFERRABLE/NOT DEFERRABLE)
- Retry policy for Postgres locking exceptions
See the quickstart below or the docs for examples.
Quickstart
After installation, set transaction characteristics using pgtransaction.atomic:
Isolation Levels
Set the isolation level for specific consistency guarantees:
import pgtransaction
with pgtransaction.atomic(isolation_level=pgtransaction.SERIALIZABLE):
# Do queries with SERIALIZABLE isolation...
There are three isolation levels: pgtransaction.READ_COMMITTED, pgtransaction.REPEATABLE_READ, and pgtransaction.SERIALIZABLE. By default it inherits the parent isolation level, which is Django's default of "READ COMMITTED".
Read-Only Transactions
Read-only mode can be used queries that don't modify data:
with pgtransaction.atomic(read_mode=pgtransaction.READ_ONLY):
# Can only read, not write
results = MyModel.objects.all()
Deferrable Transactions
Prevent serialization failures for long-running queries by blocking:
with pgtransaction.atomic(
isolation_level=pgtransaction.SERIALIZABLE,
read_mode=pgtransaction.READ_ONLY,
deferrable=pgtransaction.DEFERRABLE
):
# Long-running read-only query that won't cause serialization conflicts
analytics_data = expensive_query()
Note: DEFERRABLE only works with SERIALIZABLE isolation level and READ_ONLY mode.
Retries for Concurrent Updates
When using stricter isolation levels like pgtransaction.SERIALIZABLE, Postgres will throw serialization errors upon concurrent updates to rows. Use the argument with the decorator to retry these failures: