0
0
Djangoframework~10 mins

Primary key behavior in Django - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Primary key behavior
Define Model
Primary Key Field?
Use defined
Save instance
Assign PK value
PK must be unique
Instance saved in DB
This flow shows how Django handles primary keys: if you define one, it uses that; if not, it adds an 'id' field automatically. The primary key must be unique for each saved instance.
Execution Sample
Django
class Book(models.Model):
    title = models.CharField(max_length=100)

book = Book(title='Django Basics')
book.save()
Defines a model without a primary key field, so Django adds an 'id' automatically when saving.
Execution Table
StepActionPrimary Key FieldPK Value Before SavePK Value After SaveDB State
1Define Book modelNo explicit PKNoneNoneModel ready, no data
2Create Book instanceNo explicit PKNoneNoneInstance created, unsaved
3Call save()No explicit PKNone1 (auto-assigned)Book with id=1 saved
4Create another Book instanceNo explicit PKNoneNoneSecond instance created, unsaved
5Call save() on second instanceNo explicit PKNone2 (auto-assigned)Book with id=2 saved
6Define model with explicit PKYes, e.g. isbnUser valueUser valueInstance saved with user PK
7Try saving duplicate PKYesExisting PKErrorSave fails due to PK uniqueness
8End---No further saves
💡 Execution stops because all instances are saved or error occurs on duplicate PK
Variable Tracker
VariableStartAfter Step 3After Step 5After Step 6After Step 7Final
Book.idNone12--2
Book.isbn---User setError on duplicateUser set or error
DB entriesEmpty1 entry (id=1)2 entries (id=1,2)Entry with user PKNo new entry on error2 or error
Key Moments - 3 Insights
Why does Django add an 'id' field if I don't define a primary key?
Django requires a primary key for each model to uniquely identify records. If you don't define one, it automatically adds an 'id' field as an integer primary key. See execution_table rows 1-3.
What happens if I try to save two instances with the same primary key value?
The database enforces uniqueness on primary keys. Saving a duplicate primary key causes an error and the save fails. See execution_table row 7.
Can I use a field other than 'id' as the primary key?
Yes, you can define any field as primary key by setting primary_key=True. Django then uses that field instead of adding 'id'. See execution_table row 6.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the primary key value after saving the first Book instance?
A1
BNone
C0
DAuto-generated string
💡 Hint
Check execution_table row 3 under 'PK Value After Save'
At which step does Django assign a primary key automatically?
AStep 1
BStep 3
CStep 2
DStep 6
💡 Hint
Look at when 'PK Value After Save' changes from None to a number in execution_table
If you define a field as primary key, what happens to the 'id' field?
AIt becomes a foreign key
BIt is still added automatically
CIt is removed and not added
DIt duplicates the primary key field
💡 Hint
Refer to concept_flow where 'Primary Key Field?' decision leads to using defined PK or adding 'id'
Concept Snapshot
Django models require a primary key (PK) to uniquely identify records.
If no PK is defined, Django adds an 'id' field automatically.
You can define any field as PK by setting primary_key=True.
PK values must be unique; duplicates cause save errors.
PK is assigned when saving the instance to the database.
Full Transcript
In Django, every model needs a primary key to uniquely identify each record. If you don't define one, Django automatically adds an 'id' field as an integer primary key. When you create and save a model instance without a defined primary key, Django assigns a unique 'id' value starting from 1. If you define a field as primary key by setting primary_key=True, Django uses that field instead and does not add the 'id' field. The primary key value must be unique for each record; trying to save a duplicate primary key causes an error and the save fails. This behavior ensures each record can be uniquely retrieved and managed in the database.