[Django]-Looking for read-write lock in Django using PostgreSQL, e.g., SELECT FOR SHARE

0đź‘Ť

Can’t you wrap the logic in pl/pgsql function that uses select for share and you then call the function from django?

👤steve

0đź‘Ť

  1. Is there a good reason this was not implemented in the Django-ORM?

The ticket you’ve posted probably provides the reason: no one is motivated enough to write a patch.

  1. Does anyone know any third party library for this?

Not me, sorry.
And if by any chance you are thinking about ditching Django for some other ORM then you must ask yourself: “There is a feature I need that’s missing in Django… what features will I miss in this other ORM?”

  1. Or any easy work around?

Probably not. But here are some options:

  1. Every ORM I know has an escape hatch to raw SQL. You probably know that, but reluctant to use it… But, as you also lack the motivation to make a pull request, that probably means that you do not have hundreds of requests that require SELECT FOR SHARE functionality. So you should consider it. Performing raw SQL queries
  2. Stored procedures as steve mentioned
    https://docs.djangoproject.com/en/3.0/topics/db/sql/#calling-stored-procedures
  3. The last comment on the ticked you’ve posted is from a man (David Schwärzle) who claims that he has a solution (not for PostgreSQL specifically but a solution nevertheless)… maybe you should try and contact him.
  4. Haven’t tried it, but probably the way you can add the desired functionality is by Writing your own Query Expressions
👤x00

0đź‘Ť

You can easily implement with a raw query.

from django.db import connection

query = f"""SELECT  * FROM "appname_modelname" WHERE id={obj_id} FOR SHARE""" 
with connection.cursor() as cursor:
   cursor.execute(query, None)

obj_id is python variable.
appname_modelname is name of table created in your db by django. Django by default combines lowercased app name and model name with underscore for table name.

Leave a comment