Home > Database > Mysql Tutorial > How Can I Replace Django\'s Auto-Incrementing Primary Key with a Unique, Secure Integer ID for Specific Models?

How Can I Replace Django\'s Auto-Incrementing Primary Key with a Unique, Secure Integer ID for Specific Models?

Mary-Kate Olsen
Release: 2024-11-26 02:41:09
Original
611 people have browsed it

How Can I Replace Django's Auto-Incrementing Primary Key with a Unique, Secure Integer ID for Specific Models?

Replace Django's Primary Key with a Unique Integer for Specific Tables

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.

Requirements

  • Retain primary key field type as Integer.
  • Minimize performance overhead by hashing the primary key only once upon record insertion.
  • Use an irreversible hashing algorithm.
  • Ensure uniqueness within a specific table rather than globally.
  • Keep the hashed value concise to avoid lengthy URLs.

Approach: Timestamp-based ID Generation

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.

Code Implementation

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
Copy after login

Model Definition:

class MyClass(models.Model):
    id = models.BigIntegerField(default=make_id, primary_key=True)
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template