sthompson232
sthompson232

Reputation: 62

How to sort queryset based on foreign key with no duplicates

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

Answers (2)

willeM_ Van Onsem
willeM_ Van Onsem

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

mr blu
mr blu

Reputation: 469

you can use .distinct('review')

Upvotes: 0

Related Questions