From 63172ecf0015ee0f8c9aef395fd3793d1af6e9ed Mon Sep 17 00:00:00 2001 From: Mouse Reeve Date: Tue, 11 May 2021 13:54:38 -0700 Subject: [PATCH] Fixes ratings on shelf pages --- bookwyrm/templates/user/shelf/shelf.html | 8 +++++--- bookwyrm/views/shelf.py | 20 ++++++++++++++++---- 2 files changed, 21 insertions(+), 7 deletions(-) diff --git a/bookwyrm/templates/user/shelf/shelf.html b/bookwyrm/templates/user/shelf/shelf.html index 639ab502f..86610629c 100644 --- a/bookwyrm/templates/user/shelf/shelf.html +++ b/bookwyrm/templates/user/shelf/shelf.html @@ -79,7 +79,9 @@ {% trans "Shelved" %} {% trans "Started" %} {% trans "Finished" %} - {% if ratings %}{% trans "Rating" %}{% endif %} + {% if request.user.is_authenticated %} + {% trans "Rating" %} + {% endif %} {% if shelf.user == request.user %} {% endif %} @@ -108,9 +110,9 @@ {{ read_through.finish_date | naturalday |default_if_none:""}} - {% if ratings %} + {% if request.user.is_authenticated %} - {% include 'snippets/stars.html' with rating=ratings|dict_key:book.id %} + {% include 'snippets/stars.html' with rating=book.rating %} {% endif %} {% if shelf.user == request.user %} diff --git a/bookwyrm/views/shelf.py b/bookwyrm/views/shelf.py index 5312ac212..758e290ed 100644 --- a/bookwyrm/views/shelf.py +++ b/bookwyrm/views/shelf.py @@ -2,6 +2,7 @@ from collections import namedtuple from django.db import IntegrityError +from django.db.models import Count, OuterRef, Subquery, F, Q from django.contrib.auth.decorators import login_required from django.core.paginator import Paginator from django.http import HttpResponseBadRequest, HttpResponseNotFound @@ -37,30 +38,41 @@ class Shelf(View): return HttpResponseNotFound() if not shelf.visible_to_user(request.user): return HttpResponseNotFound() + books = shelf.books # this is a constructed "all books" view, with a fake "shelf" obj else: FakeShelf = namedtuple( "Shelf", ("identifier", "name", "user", "books", "privacy") ) books = models.Edition.objects.filter( + # privacy is ensured because the shelves are already filtered above shelfbook__shelf__in=shelves.all() ).distinct() shelf = FakeShelf("all", _("All books"), user, books, "public") - is_self = request.user == user - if is_api_request(request): return ActivitypubResponse(shelf.to_activity(**request.GET)) + reviews = privacy_filter( + request.user, + models.Review.objects.filter( + user=user, + rating__isnull=False, + book__id=OuterRef("id"), + ), + ).order_by("-published_date") + + books = books.annotate(rating=Subquery(reviews.values("rating")[:1])) + paginated = Paginator( - shelf.books.order_by("-updated_date"), + books.order_by("-updated_date"), PAGE_LENGTH, ) page = paginated.get_page(request.GET.get("page")) data = { "user": user, - "is_self": is_self, + "is_self": request.user == user, "shelves": shelves.all(), "shelf": shelf, "books": page,