使用django 实现计数器功能

select_for_update

Returns a queryset that will lock rows until the end of the transaction, generating a SELECT … FOR UPDATE SQL statement on supported databases. 也就是说将会锁定相应的对象,等待完成事务才结束。

实现

注意计数器一个名字的计数器只有一个,因些要加上 unique

# models.py 

class Counter(models.Model):
    name = models.CharField(unique=True, max_length=32)
    count = models.IntegerField(default=0)



# views.py


def index(request):
      with transaction.atomic():
            p = Couter.objects.select_for_update().filter(name=request.GET.get('name')).first()
            if p is None:
                p = Counter.objects.create(name='p1')
            time.sleep(10)
            p.count = p.count + 1
            p.save()
    return HttpResponse(p.count)

参考

queryset

Loading Disqus comments...
Table of Contents