Consider two Django models: Author and Book, where Book has a foreign key to Author. If you use Author.objects.prefetch_related('book_set'), what is the main effect?
Think about how Django avoids querying the database multiple times for related objects.
prefetch_related fetches related objects in a separate query and joins them in Python, which is efficient for reverse relations like book_set.
Given the models Author and Book (with Book.author as ForeignKey), what is the number of database queries executed by this code?
authors = Author.objects.prefetch_related('book_set').all()
for author in authors:
print(len(author.book_set.all()))Remember how prefetch_related works internally with separate queries.
prefetch_related runs one query for the main model and one for the related model, then combines results in Python, so total 2 queries.
Given models Author and Book where Book.author is a ForeignKey, what is wrong with this query?
Author.objects.prefetch_related('books').all()Assuming no related_name is set on Book.author.
Check the default reverse relation name Django uses when no related_name is set.
Without a related_name, Django uses modelname_set as the reverse relation name, so books is invalid.
Given models Author, Book, and Chapter where Book has ForeignKey to Author and Chapter has ForeignKey to Book, which syntax correctly prefetches all books and their chapters for authors?
Think about how to specify nested relations in prefetch_related.
Use double underscores to chain reverse relations in prefetch_related. Option A is correct syntax.
When prefetching a reverse relation in Django, why might you use Prefetch with a custom queryset instead of a simple string?
Consider why you might want to control which related objects are fetched.
The Prefetch object lets you specify a custom queryset to filter, order, or annotate related objects before they are attached, improving query control.