Django:如何锁定行以供阅读?

标签 django database sqlite locking

我的表包含并发工作人员的“任务”。所以工作人员应该能够从表中“获取”任务,这意味着自动检查任务是否存在,如果存在,则将其删除。其他工作人员应该被锁定,直到这个原子过程完成。如何在 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/

相关文章:

python - 如何在 django python 中用 json 替换 simplejson?

angular - 在生产模式Electron + Angular中找不到sqlite文件

c - 我应该如何在 C 中使用 Sqlite "PRAGMA integrity_check"

android - 使用 activeAndroid 更新多列

python - 如何从 Django 查询集中检索值?

django - 如何向第三方应用程序模型添加字段?

sql-server - 多个应用程序使用一个数据库?

sql - 如何对我创建的分布式数据库表应用全局查询

php - 多次使用 LastInsertId,PHP PDO

database - Django 中的动态数据库路由