我的表包含并发工作人员的“任务”。所以工作人员应该能够从表中“获取”任务,这意味着自动检查任务是否存在,如果存在,则将其删除。其他工作人员应该被锁定,直到这个原子过程完成。如何在 Django 中执行这样的锁定?
我正在使用如下代码,但行未锁定读取,两个并发工作人员都进入事务,找到相同的任务,一个成功获得它,但第二个得到 OperationalError('database is locked',)
使用SQLite
class Task(models.Model):
@staticmethod
def get():
with transaction.atomic():
task = Task.objects.select_for_update().filter(...).first()
if task:
task.delete()
return task
return None
最佳答案
SQLite 不支持行级锁,部分原因是它是基于文件的数据库:
https://www.sqlite.org/atomiccommit.html
The first step toward reading from the database file is obtaining a shared lock on the database file. A "shared" lock allows two or more database connections to read from the database file at the same time. But a shared lock prevents another database connection from writing to the database file while we are reading it.
最好的办法是切换到生产质量数据库,例如 PostgreSQL :
13.3.2. Row-level Locks
In addition to table-level locks, there are row-level locks, which are listed as below with the contexts in which they are used automatically by PostgreSQL.
关于Django:如何锁定行以供阅读?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51433501/