How to perform table/row locks in Django

Django does not explicitly provide an API to perform table locking. In my experience, well-designed code rarely needs to lock a whole table, and most concurrency issues can be solved with row-level locking. It's an last-ditch effort: it doesn't solve concurrency, it simply kills any attempt at concurrency.

If you really need table-level locking, you can use a cursor and execute raw SQL statements:

from django.db import connection

with connection.cursor() as cursor:
    cursor.execute("LOCK TABLES %s READ", [tablename])
    try:
        ...
    finally:
        cursor.execute("UNLOCK TABLES;")