Working With Custom Primary Key in Django Models
1 min readRitij Jain

Django adds an auto-incrementing id field when a model has no explicit primary key. A lookup such as get_object_or_404(MyModel, pk=1) looks for the row whose primary key is 1. It returns a 404 if that row is missing.
A model can also use a short string as its primary key. Here’s an example that generates a URL-safe ID for each new object.
Start with a function Django can call without arguments.
utils.py
import secrets
def custom_id():
return secrets.token_urlsafe(8)Set primary_key=True on the CharField and pass the function as default=custom_id. Django calls it when a new object needs a default. The database enforces uniqueness, so a collision can still cause an insert to fail.
models.py
from django.db import models
from .utils import custom_id
class MyModel(models.Model):
id = models.CharField(primary_key=True, max_length=11, default=custom_id, editable=False)Comments
No account is required; choose a display name to join the discussion.
Comments load as you approach this section.