django中的计数器的原子增量 [英] Atomic increment of a counter in django
本文介绍了django中的计数器的原子增量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
从模型导入计数器
从django.db import transaction
@ transaction.commit_on_success
def increment_counter(name):
counter = Counter.objects.get_or_create(name = name)[0]
counter.count + = 1
counter .save()
如果我正确理解Django,这应该将事务包装在一个事务中,增加原子。但它不起作用,并且在计数器更新中有竞争条件。这个代码如何使线程安全?
解决方案
Counter.objects.get_or_create(name = name)
Counter.objects.filter(name = name).update(count = F('count')+ 1)
或使用一个F表达式:
counter = Counter.objects.get_or_create(name = name)
counter.count = F('count')+1
counter.save()
I'm trying to atomically increment a simple counter in Django. My code looks like this:
from models import Counter
from django.db import transaction
@transaction.commit_on_success
def increment_counter(name):
counter = Counter.objects.get_or_create(name = name)[0]
counter.count += 1
counter.save()
If I understand Django correctly, this should wrap the function in a transaction and make the increment atomic. But it doesn't work and there is a race condition in the counter update. How can this code be made thread-safe?
解决方案
Counter.objects.get_or_create(name = name)
Counter.objects.filter(name = name).update(count = F('count')+1)
or using an F expression:
counter = Counter.objects.get_or_create(name = name)
counter.count = F('count') +1
counter.save()
这篇关于django中的计数器的原子增量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文