django-pglock provides utilities for managing PostgreSQL locks within Django applications, including advisory locks, table locks, and tools for monitoring and managing blocking locks. It is actively maintained, with regular updates to support the latest versions of Python, Django, and PostgreSQL.
pip install django-pglockVerified import paths — ran on the pinned version, not inferred.
Demonstrates how to use `pglock.advisory` as a context manager to ensure only one instance of a critical section runs at a time. The lock ID can be any string, which `django-pglock` hashes to a 64-bit integer for PostgreSQL.
Upgrade your Python, Django, and PostgreSQL versions to match the library's requirements, or pin `django-pglock` to an older compatible version.
For transaction-level locks, use `pglock.advisory(lock_id, xact=True)`. Understand the implications: session locks can persist longer than expected if not explicitly managed, especially in connection-pooling scenarios.
Wrap `pglock.model` calls within `django.db.transaction.atomic()` or similar transaction management. For example: `with transaction.atomic(): pglock.model('app_label.ModelName')`.Use a consistent naming convention for lock IDs, such as `app_name.module_name.function_name` or `app_name.resource_id.operation`.
Design your locking strategy to acquire locks in a consistent order whenever multiple resources are involved. Use `timeout` and `side_effect` arguments to handle contention gracefully, such as raising an error (`pglock.Raise`) or skipping execution (`pglock.Skip`) rather than waiting indefinitely.