November 8, 2010

Providing uniqueness of different objects across one database

Recently I needed to add facebook comments box for different pages (which were showing models of different classes). All of them needed some unique ID, to provide unique comments for each object. So at first I was thinking about applying GUUID for the db, but it looked like overcomplicating the problem. So I came up with this:

class GUUID(models.Model):
    guuid = models.PositiveSmallIntegerField(_(u"Dummy GUUID"), default=1)

It's a dummy model class with only one field (set to 1, but you can use it to provide some additional functionality). Ok, but where's our uniqueness ?

class Celebrity(BaseObject):
    uniq = models.IntegerField(blank=False, editable=False)

Here it is. Each model has a 'uniq' field set to integer field (u can use PositiveInteger if you want to). Then in save method of each object we add this :

    def save(self, *args, **kwargs):
        if not self.uniq:
            guuid = GUUID()
            self.uniq =            
        super(Celebrity, self).save(*args, **kwargs)

Now when we save object, we check fo existence of 'uniq' field. If it is null, then we create a new GUUID object and set it's id as the value of 'uniq'.

No comments:

Post a Comment