Recall & Review
beginner
What is a ForeignKey in Django models?
A ForeignKey is a field used to create a many-to-one relationship between two models. It links one model to another by storing the related model's primary key.
Click to reveal answer
beginner
How do you access related objects in a one-to-many relationship in Django?
You use the related manager on the 'one' side to access all related 'many' objects. For example, if a Book has a ForeignKey to Author, you can get all books of an author with author.book_set.all().
Click to reveal answer
intermediate
What does select_related() do in Django queries?
select_related() performs a SQL join and fetches related objects in the same query, reducing database hits for foreign key and one-to-one relationships.
Click to reveal answer
intermediate
When should you use prefetch_related() in Django?
Use prefetch_related() to fetch many-to-many or reverse foreign key relationships efficiently. It runs separate queries and joins in Python to reduce database hits.
Click to reveal answer
beginner
How do you filter objects based on related model fields in Django?
You use double underscores to span relationships in filter() calls. For example, Book.objects.filter(author__name='Alice') filters books where the related author's name is Alice.
Click to reveal answer
Which Django method fetches related objects in the same database query for ForeignKey relationships?
✗ Incorrect
select_related() uses SQL joins to fetch related objects in one query, ideal for ForeignKey and OneToOne fields.
How do you access all related objects from the 'one' side in a one-to-many relationship?
✗ Incorrect
The related manager (like book_set) lets you get all related objects from the 'one' side.
Which method is best for optimizing queries involving many-to-many relationships?
✗ Incorrect
prefetch_related() runs separate queries and joins in Python, ideal for many-to-many relationships.
How do you filter a queryset by a field in a related model?
✗ Incorrect
Django uses double underscores to traverse relationships in filters.
What is the default related manager name for a ForeignKey from model Book to Author?
✗ Incorrect
The default related manager on the 'one' side is modelname_set, so author.book_set accesses related books.
Explain how to efficiently query related objects in Django using select_related() and prefetch_related().
Think about the type of relationship and how data is fetched.
You got /4 concepts.
Describe how to filter a Django queryset based on fields in a related model.
Focus on the syntax for accessing related fields in filters.
You got /4 concepts.