django-pglocks

raw JSON →
1.0.4 verified Mon Apr 27 auth: no python maintenance

Provides useful context managers for PostgreSQL advisory locks in Django. Version 1.0.4 (latest) released Aug 2021. Low maintenance, stable, no major changes expected.

pip install django-pglocks
error AttributeError: 'NoneType' object has no attribute 'cursor'
cause advisory_lock called outside of a database connection context (e.g., before Django is fully configured).
fix
Ensure the lock is acquired inside a view or management command where a DB connection is available.
error OperationalError: advisory lock already held by this session
cause Trying to acquire the same lock twice in the same session without releasing it (e.g., nested locks with same key).
fix
Use different keys for nested locks or avoid nesting same-key locks.
error ModuleNotFoundError: No module named 'django_pglocks'
cause Library not installed in current environment.
fix
Run pip install django-pglocks.
gotcha Advisory locks are not automatically released on transaction rollback; ensure the context manager exits properly.
fix Always use the context manager; avoid manual acquire/release.
gotcha Lock key collisions: The library hashes strings to 64-bit integers; different strings may collide (hash collision).
fix Use unique, descriptive key strings; consider prepending a namespace.
gotcha PostgreSQL advisory locks are session-level; closing the connection releases all locks. Ensure connection persistence inside the critical section.
fix Keep the same database connection active within the lock context.

Acquire a PostgreSQL advisory lock using a string key. The lock is released when the context exits.

from django_pglocks import advisory_lock

with advisory_lock('my_lock_key'):
    # critical section
    pass