In Django, the primary key is typically an auto-incremented positive integer. While this serves as a practical default, it can compromise privacy by exposing the number of entities in a database. To address this concern, a customized solution is necessary that adheres to certain requirements.
Inspired by the approach used by Instagram, a suitable solution is to generate IDs based on a combination of timestamps and random bits, providing both temporal and unique properties.
ID Generation:
START_TIME = a constant representing a Unix timestamp. def make_id(): t = int(time.time() * 1000) - START_TIME u = random.SystemRandom().getrandbits(23) id = (t << 23) | u return id
Model Definition:
class MyClass(models.Model): id = models.BigIntegerField(default=make_id, primary_key=True)
This approach provides a secure and efficient way to generate unique primary keys while addressing the specific requirements outlined in the question. Additionally, the reverse_id method can be implemented to retrieve the creation time from the ID, potentially obviating the need for an additional field.
The above is the detailed content of How Can I Replace Django\'s Auto-Incrementing Primary Key with a Unique, Secure Integer ID for Specific Models?. For more information, please follow other related articles on the PHP Chinese website!