Cache user-specific ratings
This commit is contained in:
parent
4cc35ba25e
commit
1e4aee8276
|
@ -3,6 +3,7 @@ from dataclasses import MISSING
|
||||||
import re
|
import re
|
||||||
|
|
||||||
from django.apps import apps
|
from django.apps import apps
|
||||||
|
from django.core.cache import cache
|
||||||
from django.core.exceptions import PermissionDenied
|
from django.core.exceptions import PermissionDenied
|
||||||
from django.core.validators import MaxValueValidator, MinValueValidator
|
from django.core.validators import MaxValueValidator, MinValueValidator
|
||||||
from django.db import models
|
from django.db import models
|
||||||
|
@ -373,6 +374,11 @@ class Review(BookStatus):
|
||||||
activity_serializer = activitypub.Review
|
activity_serializer = activitypub.Review
|
||||||
pure_type = "Article"
|
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):
|
class ReviewRating(Review):
|
||||||
"""a subtype of review that only contains a rating"""
|
"""a subtype of review that only contains a rating"""
|
||||||
|
|
|
@ -13,10 +13,15 @@ register = template.Library()
|
||||||
@register.filter(name="rating")
|
@register.filter(name="rating")
|
||||||
def get_rating(book, user):
|
def get_rating(book, user):
|
||||||
"""get the overall rating of a book"""
|
"""get the overall rating of a book"""
|
||||||
queryset = models.Review.privacy_filter(user).filter(
|
return cache.get_or_set(
|
||||||
book__parent_work__editions=book
|
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")
|
@register.filter(name="user_rating")
|
||||||
|
|
Loading…
Reference in New Issue