A primary key is a special field in a database table that uniquely identifies each record. It helps Django find and manage data easily.
Primary key behavior in 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.
id field as primary key.class Book(models.Model): title = models.CharField(max_length=100) # Django adds id automatically as primary key
author_id is the primary key instead of the default id.class Author(models.Model): author_id = models.CharField(max_length=10, primary_key=True) name = models.CharField(max_length=100)
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.
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.
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}")
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.
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.
Practice
Solution
Step 1: Understand Django's default behavior
Django automatically adds anidfield as a primary key if none is specified.Step 2: Confirm no error or manual step needed
No error is raised and no manual primary key is required by default.Final Answer:
Automatically adds anidfield as the primary key. -> Option BQuick Check:
Default primary key = id field [OK]
- Thinking Django raises an error without a primary key
- Assuming first field is primary key by default
- Believing manual primary key is always required
Solution
Step 1: Identify correct keyword argument
The correct argument to set a primary key isprimary_key=True.Step 2: Match with options
Onlyname = models.CharField(max_length=100, primary_key=True)usesprimary_key=Truecorrectly.Final Answer:
name = models.CharField(max_length=100, primary_key=True) -> Option AQuick Check:
Use primary_key=True to set primary key [OK]
- Using incorrect argument names like primary=True
- Confusing primary_key with other flags
- Misspelling primary_key
class Product(models.Model):
sku = models.CharField(max_length=20, primary_key=True)
name = models.CharField(max_length=100)
p = Product(sku='X123', name='Widget')
p.save()
print(Product.objects.get(pk='X123').name)
What will be printed?Solution
Step 1: Understand primary key usage
Theskufield is set as primary key, sopk='X123'looks up by sku.Step 2: Trace the query result
The object with sku 'X123' has name 'Widget', so printing.nameoutputs 'Widget'.Final Answer:
Widget -> Option DQuick Check:
Primary key lookup returns object name [OK]
- Assuming pk means id field always
- Expecting error because id field missing
- Confusing printed value with primary key value
class Customer(models.Model):
id = models.IntegerField(primary_key=True)
id = models.CharField(max_length=10, primary_key=True)Solution
Step 1: Check primary key uniqueness in model
A Django model can have only one primary key field.Step 2: Identify duplicate primary_key=True fields
Here, two fields named 'id' are declared with primary_key=True, which is invalid.Final Answer:
You cannot have two fields with primary_key=True in the same model. -> Option CQuick Check:
Only one primary key allowed per model [OK]
- Thinking multiple primary keys are allowed
- Believing primary key must be AutoField
- Assuming primary key name restrictions
email field uniquely identifies each user and acts as the primary key. Which is the best way to define this model?Solution
Step 1: Understand primary key vs unique
Primary key uniquely identifies records and is used as the main identifier.Step 2: Check options for setting email as primary key
class User(models.Model): email = models.EmailField(primary_key=True) name = models.CharField(max_length=100)setsemailas primary key directly, which is correct.class User(models.Model): email = models.EmailField(unique=True) name = models.CharField(max_length=100)only makes it unique but not primary key.class User(models.Model): id = models.AutoField(primary_key=True) email = models.EmailField(unique=True) name = models.CharField(max_length=100)keeps default id as primary key.class User(models.Model): email = models.EmailField() name = models.CharField(max_length=100) class Meta: primary_key = 'email'uses invalid Meta syntax.Final Answer:
Define email with primary_key=True in the model field. -> Option AQuick Check:
Set primary_key=True on email field to make it primary key [OK]
- Using unique=True instead of primary_key=True
- Keeping default id field as primary key
- Trying to set primary key in Meta class
Ready to prove it?
Pass the test and this pattern moves unknown
