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)