Atomic increment of a counter in django

前端 未结 6 2077
暗喜
暗喜 2020-12-04 13:04

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

@trans         


        
6条回答
  •  余生分开走
    2020-12-04 13:31

    Keeping it simple and building on @Oduvan's answer:

    counter, created = Counter.objects.get_or_create(name = name, 
                                                     defaults={'count':1})
    if not created:
        counter.count = F('count') +1
        counter.save()
    

    The advantage here is that if the object was created in the first statement, you don't have to do any further updates.

提交回复
热议问题