Atomic increment of a counter in django

前端 未结 6 2069
暗喜
暗喜 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:43

    New in Django 1.1

    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( update_fields=["count"] )
    

    Remember to Specify Which fields to update, Or you might encounter race conditions on other possible fields of the model!

    A topic on the race condition associated with this approach has been added to the official documentation.

提交回复
热议问题