My problem is as follows:
I have a car dealer A, and a db table named sold_cars. When a car is being sold I create entry in this table.
Table ha
from contextlib import contextmanager
from django.db import transaction
from django.db.transaction import get_connection
@contextmanager
def lock_table(model):
with transaction.atomic():
cursor = get_connection().cursor()
cursor.execute(f'LOCK TABLE {model._meta.db_table}')
try:
yield
finally:
cursor.close()
This is very similar to @jdepoix solution, but a but more dense.
You can use it like this:
with lock_table(MyModel):
MyModel.do_something()
Note that this only works with PostgreSQL and uses python 3.6's f-strings a.k.a. literal string interpolation.