django 中的原子事务是数据库级别的吗?

Are atomic transactions in django on database level?

我有一个 django 后端应用程序,我 运行 宁在 docker 容器上, 我在某些需要的地方使用原子事务

所以因为我的流量很大,而且有很多地方需要昂贵的计算,所以我想 运行 另一个 django 应用程序实例,并平衡负载,

我的问题是 instance1 启动了一个原子事务,而 instance2 想在同一记录上启动一个原子事务,instance2 是否看到 instance1 是运行宁一个原子事务所以请求将等到 instance1 完成?

谢谢

是的,Django 能够处理这类请求!

对于并发事务,您可以在 transaction.atomic() 块内的 managerqueryset 对象上使用 select_for_update 方法。您可以从 here.

找到关于 select_for_update 的文档

Note: Usage of transaction.atomic() with select_for_update() is used to handle concurrency and atomicity on database level.

select_for_update 在数据库级别执行以下类型的查询。

SELECT FOR UPDATE wallet where wallet.id = '1'

from django.db import transaction

user_wallet = Wallet.objects.select_for_update().get(user=request.user)  # select for update query
with transaction.atomic():   # atomic transactions block
    user_wallet.amount += Decimal('200')  # updating user's wallet amount
    user_wallet.save()

有关详细信息,请参阅 Django Database Transactions documentation