In Django, the default primary key is an auto-incremented positive integer used throughout the application. However, this publicly exposes the number of entities in the database, prompting the need for an alternative. This article addresses a specific set of requirements for an obfuscated primary key:
Instagram's method, inspired by this article, meets these requirements. The generated ID consists of:
ID Generation:
START_TIME = <unix timestamp> def make_id(): t = int(time.time()*1000) - START_TIME u = random.SystemRandom().getrandbits(23) id = (t << 23) | u return id def reverse_id(id): t = id >> 23 return t + START_TIME
Model:
class MyClass(models.Model): id = models.BigIntegerField(default=fields.make_id, primary_key=True)
The above is the detailed content of How Can I Replace Django\'s Auto-Incrementing Primary Key with a Unique, Short, Integer ID?. For more information, please follow other related articles on the PHP Chinese website!