Django ORM and locking table

前端 未结 4 1390
有刺的猬
有刺的猬 2020-12-13 14:34

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

4条回答
  •  醉酒成梦
    2020-12-13 15:00

    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.

提交回复
热议问题