如何在Django当中使用数据库锁呢?局部事务锁。通过上下文管理。
# 事务
with transaction.atomic():
# 在数据库中加锁 select * from customer where id in [11,22] for update
origin_queryset = models.Customer.objects.filter(id__in=pk_list, status=2, consultant__isnull=True).select_for_update()
if len(origin_queryset) == len(pk_list): # 确保批量添加操作的个数和移到私户的个数一致才可以。
models.Customer.objects.filter(id__in=pk_list, status=2, consultant__isnull=True).update(consultant_id=current_user_id)
flag = True
if not flag:
return HttpResponse('手速太慢了,选中的客户已被其他人申请,请重新选择')
select_for_update()就是上锁。相当于select * from customer where id in [11,22] for update。
原创文章,作者:254126420,如若转载,请注明出处:https://blog.ytso.com/tech/bigdata/278104.html