0
0
Djangoframework~5 mins

Primary key behavior in Django - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is a primary key in Django models?
A primary key is a unique identifier for each record in a database table. In Django, it uniquely identifies each model instance.
Click to reveal answer
beginner
What happens if you don't define a primary key in a Django model?
Django automatically adds an id field as an auto-incrementing primary key.
Click to reveal answer
intermediate
Can you use a field other than id as a primary key in Django?
Yes, you can set any field as the primary key by adding primary_key=True to that field.
Click to reveal answer
intermediate
What is the behavior of a primary key field with primary_key=True in Django?
It becomes unique, non-nullable, and automatically used as the identifier for model instances.
Click to reveal answer
beginner
Why should a primary key be unique and non-null in Django models?
Because it identifies each record uniquely and must always have a value to avoid confusion in data retrieval.
Click to reveal answer
What does Django do if no primary key is defined in a model?
AThrows an error
BAdds an auto-incrementing <code>id</code> field as primary key
CUses the first field as primary key
DCreates a composite key automatically
Which of these is true about a primary key field in Django?
AIt must be unique
BIt can be null
CIt can have duplicate values
DIt is optional
How do you set a custom field as a primary key in Django?
AAdd <code>unique=True</code> to the field
BSet <code>auto_increment=True</code>
CAdd <code>primary_key=True</code> to the field
DRename the field to <code>id</code>
What type of field does Django use by default for the primary key?
ABooleanField
BCharField
CForeignKey
DAutoField
Why is it important that a primary key is non-null?
ATo ensure every record can be uniquely identified
BTo speed up queries
CTo allow multiple records with the same key
DTo allow null values in other fields
Explain what a primary key is in Django and how Django handles it if you don't define one.
Think about what Django adds automatically to every model.
You got /4 concepts.
    Describe how to set a custom primary key in a Django model and what changes this causes.
    Focus on the field attribute that changes primary key behavior.
    You got /3 concepts.