ORM中的锁与事物

s21版crm的“公户转私户”用到了事物操作

from django.db import transaction

class CustomerList(View):

    def get(self, request, *args, **kwargs):

        xxx

    def post(self, request, *args, **kwargs):

        action = request.POST.get('action')
        if not hasattr(self, action):
            return HttpResponse('非法操作')
        ret = getattr(self, action)()
        if ret:
            return ret
        return self.get(request, *args, **kwargs)

    def multi_apply(self):
        # 公户转私户
        pk = self.request.POST.getlist('pk')  # [5,6]

        if models.Customer.objects.filter(consultant=self.request.user_obj).count() + len(
                pk) > settings.MAX_CUSTOMER_NUM:
            return HttpResponse('做人不能太贪心,给别人留一点。')
        # 事物操作 ##############
        try:
            with transaction.atomic():
                # 方法一
                queryset = models.Customer.objects.filter(pk__in=pk, consultant=None).select_for_update()
                if len(pk) == queryset.count():
                    queryset.update(consultant=self.request.user_obj)
                else:
                    return HttpResponse('手速太慢,客户已经被别人抢走了!')

                # 方法二
                # self.request.user_obj.customers.add(*models.Customer.objects.filter(pk__in=pk))
except Exception as e: print(e)

行级锁的操作 —— select_for_update —— 悲观锁

# Django中使用行级锁
from django.db import transaction
try:
    with transaction.atomic():
        """ 
        一系列操作
        """
        query_set = Book.objects.filter(id__gt=5).select_for_update()
        query_set

except Exception:
    pass

 

posted on 2019-05-29 20:28  江湖乄夜雨  阅读(195)  评论(0编辑  收藏  举报