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
- Model with random ID by jobs@flowgram.com 4 years, 11 months ago
- Friendly ID by willhardy 4 years, 5 months ago
- update primary key (cascade to child tables and inherited models) by variant 2 weeks, 4 days ago
- update primary key (and cascade to child tables) by guettli 1 year, 2 months ago
- BigIntegerField and BigAutoField by fnl 4 years, 5 months ago
Comments
Here are a few things I noticed:
-.models.BigIntegerField.MAX_BIGINT-1andmodels.BigIntegerField.MAX_BIGINTself.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.
#