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
- 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
Here are a few things I noticed:
-.models.BigIntegerField.MAX_BIGINT-1
andmodels.BigIntegerField.MAX_BIGINT
self.pk
).#
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.