Django Django Models & ORM 2 — Questions and Answers
Question 1: Which Django command applies pending database migrations?
- python manage.py migrate (Correct answer)
- python manage.py makemigrations
- python manage.py syncdb
- python manage.py applydb
Correct answer: python manage.py migrate
migrate applies all pending migration files to synchronize the database schema with the current state of your models.
Question 2: What is a QuerySet in Django?
- A lazy collection of database objects that can be filtered and chained (Correct answer)
- A single database row
- A SQL query string
- A database connection object
Correct answer: A lazy collection of database objects that can be filtered and chained
A QuerySet represents a collection of database rows that can be filtered, ordered, and evaluated lazily when the data is actually needed.
Question 3: Which method would you call to create and save a new model instance in one step?
- Model.objects.create() (Correct answer)
- Model.objects.new()
- Model.objects.save()
- Model.objects.insert()
Correct answer: Model.objects.create()
Model.objects.create() instantiates the model and calls save() in a single database operation.
Question 4: What does `select_related()` do in a Django QuerySet?
- Performs a SQL JOIN to fetch related objects in a single query (Correct answer)
- Lazy-loads related objects on access
- Prefetches many-to-many related objects
- Caches QuerySet results in memory
Correct answer: Performs a SQL JOIN to fetch related objects in a single query
select_related() follows ForeignKey and OneToOneField relationships and performs a SQL JOIN, reducing the number of database queries.
Question 5: Which lookup suffix checks if a field value is in a given list in Django ORM?
- __in (Correct answer)
- __contains
- __list
- __among
Correct answer: __in
The __in lookup filters objects whose field value is contained in the provided list, generating a SQL IN clause.
Question 6: What is the purpose of `prefetch_related()` in Django ORM?
- Fetches many-to-many and reverse ForeignKey relations in separate optimized queries (Correct answer)
- Performs a single JOIN query for all relations
- Caches model instances in Redis
- Pre-loads all model fields
Correct answer: Fetches many-to-many and reverse ForeignKey relations in separate optimized queries
prefetch_related() does separate queries for each relationship and performs the joining in Python, which is optimal for many-to-many and reverse FK lookups.
Which Django command applies pending database migrations?