Counter model - run multiple persistent counters

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
from django.db import models
from django.db.models import F

class Counter(models.Model):
    "For generating unique IDs"
    key = models.CharField(max_length=50, primary_key=True)
    counter = models.IntegerField(default = 0)
    
    @classmethod
    def next(cls, key = 'default'):
        "Increments and returns the next unused integer"
        try:
            cls.objects.filter(pk = key).update(counter = F('counter') + 1)
            return cls.objects.get(pk = key).counter
        except cls.DoesNotExist:
            # This could raise an integrity error in a race condition :/
            return cls.objects.create(key = key, counter = 0).counter
    
    @classmethod
    def next_hex(cls, key = 'default'):
        return hex(cls.next(key)).replace('0x', '').replace('L', '')
    
    def __unicode__(self):
        return u'%s = %s' % (self.pk, self.counter)

More like this

  1. counter templatetag by bcurtu 4 years, 5 months ago
  2. elif for smart if tag by showell 4 years, 10 months ago
  3. Model Choices Helper by pmclanahan 4 years, 2 months ago
  4. SuperChoices by willhardy 5 years, 5 months ago
  5. Templatetag startswith + message tuned by io_error 5 years, 10 months ago

Comments

jdarknet (on January 13, 2011):

Excelents, congratulations

#

(Forgotten your password?)