在Django中创建原子事务会自动创建锁吗

2024-05-20 16:24:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个代码块在里面事务处理.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


Tags: django代码视图withtablecodecustomerthis
1条回答
网友
1楼 · 发布于 2024-05-20 16:24:56

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

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固有的,应用程序的编程语言和库不能影响这一点。在

相关问题 更多 >