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

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

DDD
DDDOriginal
2024-12-03 16:51:10763browse

How Can I Replace Django's Auto-Incrementing Primary Key with a Unique, Short, Integer ID?

Replacing Django's Primary Key with a Unique Integer

Problem Outline

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:

  • Integer data type
  • Avoidance of hashing/unhashing for every read/write/comparison
  • One-time hashing at record insertion
  • Unique hashed value within a specific table
  • Minimal length for short URLs

Proposed Solution

Instagram's method, inspired by this article, meets these requirements. The generated ID consists of:

  • 41 bits for a time-based component
  • 23 bits chosen at random

Code Implementation

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!

Statement:
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