Random object IDs using an abstract base model

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
class ObfuscatedPKModel(models.Model):
    class Meta:
        abstract = True
        
    id = models.BigIntegerField(primary_key = True, db_index = True)
    
    def save(self, *args, **kwargs):
        if not self.pk:
            kwargs["force_insert"] = True
            while True:
                # Avoid generating 0
                self.pk = random.randint(-models.BigIntegerField.MAX_BIGINT - 1, models.BigIntegerField.MAX_BIGINT) or models.BigIntegerField.MAX_BIGINT
                try:
                    super(ObfuscatedPKModel, self).save(*args, **kwargs)
                    break
                except IntegrityError:
                    logger.info("Duplicate PK situation averted.")
                    continue
        else:
            super(ObfuscatedPKModel, self).save(*args, **kwargs)

More like this

  1. Model with random ID by jobs@flowgram.com 4 years, 11 months ago
  2. Friendly ID by willhardy 4 years, 5 months ago
  3. update primary key (cascade to child tables and inherited models) by variant 2 weeks, 3 days ago
  4. update primary key (and cascade to child tables) by guettli 1 year, 2 months ago
  5. BigIntegerField and BigAutoField by fnl 4 years, 5 months ago

Comments

willhardy (on July 15, 2011):

Here are a few things I noticed:

  1. (Obscure bug) You leave open the possibility of pk = 0, which some parts of Django and third party code might not expect. It also means the next time you save the object, it will be assigned a new random primary key (and be duplicated in the database).
  2. (Not too important) The hardcoded limits for bigintegerfield can be better accessed at -.models.BigIntegerField.MAX_BIGINT-1 and models.BigIntegerField.MAX_BIGINT
  3. (not important) the first two pk assignments are unnecessary (but change if statement to use self.pk).
  4. (completely optional) You might like to encode the gigantic integer as a base36 string when including it in the URL.

#

elver (on July 15, 2011):

Thanks for the comments! I rewrote it, taking your comments into account, and also removing the highly remote possibility of two threads happening upon the same PK by chance and overwriting one another's data.

#

(Forgotten your password?)