Reputation: 62
I would like to feature the 5 most recently reviewed books on my website. I am trying to order the books based on the time they were reviewed. The problem is if a book has recently been reviewed more than once, it will appear more than once. How do I get 5 unique books from this query? (I tried adding .distinct() to the query and it didn't work!)
reviewed = Book.objects.order_by('-review__date_posted')[:5]
Upvotes: 1
Views: 509
Reputation: 476544
You can order by the largest date_posted
of the review
, so:
from django.db.models import Max
Book.objects.annotate(
last_review=Max('review__date_posted')
).order_by('-last_review')[:5]
Upvotes: 3