【问题标题】:Why the select for update not working in django mysql?为什么选择更新在 django mysql 中不起作用?
【发布时间】:2018-09-28 02:58:17
【问题描述】:

我有一张如下表

select id, name from node;
+----+------+
| id | name |
+----+------+
|  5 | na   |
+----+------+

然后定义下面的函数

>>> def foo_with_sfu(seconds):
...     with transaction.atomic():
...         node = Node.objects.select_for_update().filter(pk=5)
...         time.sleep(seconds)
...         node = Node.objects.get(pk=5)
...         print(node.name)
... 

我希望 select_for_update 会锁定行 pk=5,所以如果我在 time.sleep 期间打开另一个控制台来更改 node.name,更改操作将被阻止。

但实际上当我运行该函数,并在 time.sleep 期间在另一个控制台中运行 update sql 时,更新并没有被阻止。

似乎选择更新没有锁定行。为什么?

【问题讨论】:

    标签: mysql django transactions


    【解决方案1】:

    您的select_for_update() 查询永远不会被评估,因此永远不会在数据库上执行锁定。请参阅 the documentation 了解查询集的评估时间和方式。

    如果您只是将调用包装在查询集评估函数中,您的测试应该可以工作。例如:

    with transaction.atomic():
        node = list(Node.objects.select_for_update().filter(pk=5))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-05-13
      • 2015-02-11
      • 1970-01-01
      • 2018-04-30
      • 1970-01-01
      • 2021-12-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多