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
- Template tag - list punctuation for a list of items by shapiromatron 10 months, 1 week ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 2 weeks ago
- Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
- Help text hyperlinks by sa2812 1 year, 6 months ago
Comments
Excelents, congratulations
#
Please login first before commenting.