gpt4 book ai didi

python - 在django中创建原子事务是否自动创建一个锁

转载 作者:行者123 更新时间:2023-11-28 23:08:19 25 4
gpt4 key购买 nike

我在 View 中的 transaction.atomic() 中有一个代码块。我的问题是 django 是否在幕后创建了一些内置表锁定。

with transaction.atomic():
#code block that does database operations
update_user() #this updates user table
create_customer_products() #this updates user id to customer products table

原因是我在运行代码块时收到“超出锁定等待超时;尝试重新启动事务”错误。

设置是centos上的django mysql

最佳答案

为了在 innodb 表中修改或插入记录,事务需要获取 exclusive lock在 MySQL 中:

UPDATE ... WHERE ... sets an exclusive next-key lock on every record the search encounters. However, only an index record lock is required for statements that lock rows using a unique index to search for a unique row.

...

INSERT sets an exclusive lock on the inserted row. This lock is an index-record lock, not a next-key lock (that is, there is no gap lock) and does not prevent other sessions from inserting into the gap before the inserted row.

如果相同的记录(或间隙)已经被另一个事务锁定,则MySQL等待释放锁或发生上述超时。

根据上面的代码,我们无法判断哪里出了问题(如果有的话)。你可以看看innodb status monitor以获得更多信息,但如果没有僵局,它的使用也将受到限制。

此行为是 MySQL 固有的,应用程序的编程语言和库不会对此产生影响。

关于python - 在django中创建原子事务是否自动创建一个锁,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46582536/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com