Cache user-specific ratings

This commit is contained in:
Mouse Reeve 2022-01-17 12:17:24 -08:00
parent 4cc35ba25e
commit 1e4aee8276
2 changed files with 14 additions and 3 deletions

View file

@ -3,6 +3,7 @@ from dataclasses import MISSING
import re
from django.apps import apps
from django.core.cache import cache
from django.core.exceptions import PermissionDenied
from django.core.validators import MaxValueValidator, MinValueValidator
from django.db import models
@ -373,6 +374,11 @@ class Review(BookStatus):
activity_serializer = activitypub.Review
pure_type = "Article"
def save(self, *args, **kwargs):
"""clear rating caches"""
cache.delete(f"book-rating-{self.book.parent_work.id}-*")
super().save(*args, **kwargs)
class ReviewRating(Review):
"""a subtype of review that only contains a rating"""

View file

@ -13,10 +13,15 @@ register = template.Library()
@register.filter(name="rating")
def get_rating(book, user):
"""get the overall rating of a book"""
queryset = models.Review.privacy_filter(user).filter(
book__parent_work__editions=book
return cache.get_or_set(
f"book-rating-{book.parent_work.id}-{user.id}",
lambda u, b: models.Review.privacy_filter(u)
.filter(book__parent_work__editions=b)
.aggregate(Avg("rating"))["rating__avg"],
user,
book,
timeout=15552000,
)
return queryset.aggregate(Avg("rating"))["rating__avg"]
@register.filter(name="user_rating")