This small snippet can be implemented in your Django project to handle locks. It is particularly useful for replacing Redis locks, reducing dependency overhead. To use this snippet, simply copy and adapted to your Django project.
The hash_string function is used to convert a string value into a numerical hash value, as PostgreSQL advisory lock mechanism requires an integer.
Tested on Python3.11 and Django4
Learn more about advisory locks in: