Login

Random object IDs using an abstract base model

Author:
elver
Posted:
July 15, 2011
Language:
Python
Version:
1.3
Tags:
primary-key random obfuscated model abstract models obfuscation ID
Score:
-1 (after 1 ratings)

To put obfuscated primary keys in any class, simply inherit from this one. For example:

class Offer(ObfuscatedPKModel)

You can match for these bigint primary keys in your urls.py like this:

'^offer/(?P<offer_pk>[0-9-]+)$'

 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 6 years, 10 months ago
  2. Use the primary key in FileField and ImageField filenames by exogen 6 years, 6 months ago
  3. Friendly ID by willhardy 6 years, 4 months ago
  4. uuid model field by newspire 6 years, 4 months ago
  5. BigIntegerField and BigAutoField by fnl 6 years, 4 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.

#

Please login first before commenting.