Bird
Raised Fist0
Djangoframework~10 mins

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

Choose your learning style10 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.

Practice

(1/5)
1. What does Django do if you do not specify a primary key in your model?
easy
A. Uses the first field defined as the primary key.
B. Automatically adds an id field as the primary key.
C. Raises an error and refuses to create the model.
D. Requires you to manually add a primary key later.

Solution

  1. Step 1: Understand Django's default behavior

    Django automatically adds an id field as a primary key if none is specified.
  2. Step 2: Confirm no error or manual step needed

    No error is raised and no manual primary key is required by default.
  3. Final Answer:

    Automatically adds an id field as the primary key. -> Option B
  4. Quick Check:

    Default primary key = id field [OK]
Hint: Remember: Django adds id automatically if no primary key [OK]
Common Mistakes:
  • Thinking Django raises an error without a primary key
  • Assuming first field is primary key by default
  • Believing manual primary key is always required
2. Which of the following is the correct way to set a field as the primary key in a Django model?
easy
A. name = models.CharField(max_length=100, primary_key=True)
B. name = models.CharField(max_length=100, key_primary=True)
C. name = models.CharField(max_length=100, primary=True)
D. name = models.CharField(max_length=100, is_primary=True)

Solution

  1. Step 1: Identify correct keyword argument

    The correct argument to set a primary key is primary_key=True.
  2. Step 2: Match with options

    Only name = models.CharField(max_length=100, primary_key=True) uses primary_key=True correctly.
  3. Final Answer:

    name = models.CharField(max_length=100, primary_key=True) -> Option A
  4. Quick Check:

    Use primary_key=True to set primary key [OK]
Hint: Use primary_key=True exactly to set primary key [OK]
Common Mistakes:
  • Using incorrect argument names like primary=True
  • Confusing primary_key with other flags
  • Misspelling primary_key
3. Given this model:
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?
medium
A. None
B. X123
C. Error: No primary key field found
D. Widget

Solution

  1. Step 1: Understand primary key usage

    The sku field is set as primary key, so pk='X123' looks up by sku.
  2. Step 2: Trace the query result

    The object with sku 'X123' has name 'Widget', so printing .name outputs 'Widget'.
  3. Final Answer:

    Widget -> Option D
  4. Quick Check:

    Primary key lookup returns object name [OK]
Hint: pk uses the primary key field, here sku, to find object [OK]
Common Mistakes:
  • Assuming pk means id field always
  • Expecting error because id field missing
  • Confusing printed value with primary key value
4. What is wrong with this model definition?
class Customer(models.Model):
    id = models.IntegerField(primary_key=True)
    id = models.CharField(max_length=10, primary_key=True)
medium
A. You must use AutoField for primary keys, not IntegerField or CharField.
B. Primary keys cannot be named 'id'.
C. You cannot have two fields with primary_key=True in the same model.
D. The model is missing a Meta class to define primary key.

Solution

  1. Step 1: Check primary key uniqueness in model

    A Django model can have only one primary key field.
  2. Step 2: Identify duplicate primary_key=True fields

    Here, two fields named 'id' are declared with primary_key=True, which is invalid.
  3. Final Answer:

    You cannot have two fields with primary_key=True in the same model. -> Option C
  4. Quick Check:

    Only one primary key allowed per model [OK]
Hint: Only one field can have primary_key=True in a model [OK]
Common Mistakes:
  • Thinking multiple primary keys are allowed
  • Believing primary key must be AutoField
  • Assuming primary key name restrictions
5. You want to create a Django model where the email field uniquely identifies each user and acts as the primary key. Which is the best way to define this model?
hard
A.
class User(models.Model):
    email = models.EmailField(primary_key=True)
    name = models.CharField(max_length=100)
B.
class User(models.Model):
    email = models.EmailField(unique=True)
    name = models.CharField(max_length=100)
C.
class User(models.Model):
    id = models.AutoField(primary_key=True)
    email = models.EmailField(unique=True)
    name = models.CharField(max_length=100)
D.
class User(models.Model):
    email = models.EmailField()
    name = models.CharField(max_length=100)
    class Meta:
        primary_key = 'email'

Solution

  1. Step 1: Understand primary key vs unique

    Primary key uniquely identifies records and is used as the main identifier.
  2. 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)
    sets email as 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.
  3. Final Answer:

    Define email with primary_key=True in the model field. -> Option A
  4. Quick Check:

    Set primary_key=True on email field to make it primary key [OK]
Hint: Use primary_key=True on email field to make it primary key [OK]
Common Mistakes:
  • Using unique=True instead of primary_key=True
  • Keeping default id field as primary key
  • Trying to set primary key in Meta class
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard