A primary key is a special field in a database table that uniquely identifies each record. It helps Django find and manage data easily.
0
0
Primary key behavior in Django
Introduction
When you want to uniquely identify each item in a database table.
When you need to link records between tables using relationships.
When you want to ensure no two records have the same identity.
When you want Django to automatically create unique IDs for your data.
Syntax
Django
class MyModel(models.Model): id = models.AutoField(primary_key=True) # other fields here
Django automatically adds an id field as a primary key if you don't define one.
You can set any field as primary key by adding primary_key=True.
Examples
This model uses the default
id field as primary key.Django
class Book(models.Model): title = models.CharField(max_length=100) # Django adds id automatically as primary key
Here,
author_id is the primary key instead of the default id.Django
class Author(models.Model): author_id = models.CharField(max_length=10, primary_key=True) name = models.CharField(max_length=100)
Using a custom string field as primary key.
Django
class Product(models.Model): sku = models.CharField(max_length=20, primary_key=True) name = models.CharField(max_length=100) # Using a custom string field as primary key.
Sample Program
This example shows a model with a custom primary key student_number. We create and save a student, then retrieve it using the primary key.
Django
from django.db import models class Student(models.Model): student_number = models.CharField(max_length=10, primary_key=True) name = models.CharField(max_length=100) # Usage example (in Django shell or view): # Create a student student = Student(student_number='S12345', name='Alice') student.save() # Retrieve student by primary key found_student = Student.objects.get(student_number='S12345') print(f"Student: {found_student.name}, Number: {found_student.student_number}")
OutputSuccess
Important Notes
Primary key fields must be unique and not null.
Using AutoField lets Django auto-increment IDs for you.
Choosing a meaningful primary key can help with data clarity but must be unique.
Summary
Primary keys uniquely identify each record in a Django model.
Django adds an id field automatically if you don't specify one.
You can set any field as primary key by adding primary_key=True.