← Fullstack with Vue.jsQuestion 57 of 62
Given a Book model with a ForeignKey to Author, how do you query the most expensive book per author in Django ORM?
📘 Explanation
A correlated subquery with OuterRef links each author in the outer query to their own books in the inner query, correctly fetching only the most expensive book per author. The wrong answers using distinct() with ordering, or annotate() with Max() and filtering, don't reliably isolate one book per author or can match multiple rows incorrectly, and the values().annotate() approach returns aggregate data rather than actual book objects.
Related questions
- When do you use selectrelated() vs prefetchrelated() in Django?
- What does QuerySet.defer() do in Django ORM?
- What does Django's extra() method do, and when would you use it?
- What's the difference between annotate() vs values().annotate() in Django ORM?
- When you call selectrelated("author") on a Book queryset, what kind of SQL join does Django generate? Does it always…
← PreviousNo login needed