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)