[Fixed]-Django 1.8: Join latest entry to foreign key

1👍

I was able to solve this by explicitly defining the prefetch queryset to get just the latest book for each author. This lets me use .all() which will only contain the latest book (or none), and doesn’t cause another query.

latest_books = Book.objects.annotate(latest=Max('author__book__pubdate')).filter(pubdate=F('latest'))

for a in Author.objects.prefetch_related(Prefetch('book_set', queryset=b_query)):
    a.book_set.all()[0]

Leave a comment