From 4cc35ba25ee35f7d452e082ee3598c2ac9b65a75 Mon Sep 17 00:00:00 2001 From: Mouse Reeve Date: Mon, 17 Jan 2022 11:53:00 -0800 Subject: [PATCH] Cache query for author's books --- bookwyrm/models/book.py | 5 +++++ bookwyrm/views/author.py | 21 ++++++++++++++++----- 2 files changed, 21 insertions(+), 5 deletions(-) diff --git a/bookwyrm/models/book.py b/bookwyrm/models/book.py index 8d1b70ae..ffc03d3e 100644 --- a/bookwyrm/models/book.py +++ b/bookwyrm/models/book.py @@ -342,6 +342,11 @@ class Edition(Book): # set rank self.edition_rank = self.get_rank() + # clear author cache + if self.id: + for author_id in self.authors.values_list("id", flat=True): + cache.delete(f"author-books-{author_id}") + return super().save(*args, **kwargs) @classmethod diff --git a/bookwyrm/views/author.py b/bookwyrm/views/author.py index 2acb3b19..9bc95b79 100644 --- a/bookwyrm/views/author.py +++ b/bookwyrm/views/author.py @@ -12,6 +12,7 @@ from bookwyrm import forms, models from bookwyrm.activitypub import ActivitypubResponse from bookwyrm.connectors import connector_manager from bookwyrm.settings import PAGE_LENGTH +from bookwyrm.utils import cache from bookwyrm.views.helpers import is_api_request @@ -30,14 +31,24 @@ class Author(View): parent_work=OuterRef("parent_work") ).order_by("-edition_rank") - books = ( - models.Edition.viewer_aware_objects(request.user) - .filter(Q(authors=author) | Q(parent_work__authors=author)) + book_ids = cache.get_or_set( + f"author-books-{author.id}", + lambda a: models.Edition.objects.filter( + Q(authors=a) | Q(parent_work__authors=a) + ) .annotate(default_id=Subquery(default_editions.values("id")[:1])) .filter(default_id=F("id")) - .order_by("-first_published_date", "-published_date", "-created_date") + .distinct() + .values_list("id", flat=True), + author, + timeout=15552000, + ) + + books = ( + models.Edition.objects.filter(id__in=book_ids) + .order_by("-published_date", "-first_published_date", "-created_date") .prefetch_related("authors") - ).distinct() + ) paginated = Paginator(books, PAGE_LENGTH) page = paginated.get_page(request.GET.get("page"))