Login

Counter model - run multiple persistent counters

Author:
simon
Posted:
June 17, 2009
Language:
Python
Version:
1.0
Tags:
database counters
Score:
0 (after 0 ratings)

Sometimes you just need to count things (or create unique-for-your-application IDs). This model class allows you to run as many persistent counters as you like. Basic usage looks like this:

>>> Counter.next()
0
>>> Counter.next()
1L
>>> Counter.next()
2L

That uses the "default" counter. If you want to create and use a different counter, pass its name as a string as the parameter to the method:

>>> Counter.next('hello')
0
>>> Counter.next('hey')
0
>>> Counter.next('hello')
1L
>>> Counter.next('hey')
1L
>>> Counter.next('hey')
2L

You can also get the value as hex (if you want slightly shorter IDs, for use in URLs for example):

>>> Counter.next_hex('some-counter-that-is-quite-high')
40e
 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 5 years, 8 months ago
  2. elif for smart if tag by showell 6 years, 1 month ago
  3. Model Choices Helper by pmclanahan 5 years, 6 months ago
  4. SuperChoices by willhardy 6 years, 8 months ago
  5. Templatetag startswith + message tuned by io_error 7 years, 1 month ago

Comments

jdarknet (on January 13, 2011):

Excelents, congratulations

#

Please login first before commenting.