mirror of
https://github.com/bookwyrm-social/bookwyrm.git
synced 2024-09-27 05:50:05 +00:00
fc3b609ada
The original system customized how a rating is displayed to every user based on the privacy settings of the reviews and, relatedly, who the user follows. This is cool, but the query is too complicated to load in sessions, and the initial load, which isn't mitigated by caching, is too much and causes timeouts for many users. Also the cache clearing wasn't working correctly because I put in a wildcard, which does not work.
42 lines
990 B
Python
42 lines
990 B
Python
""" template filters """
|
|
from django import template
|
|
from django.db.models import Avg
|
|
|
|
from bookwyrm import models
|
|
from bookwyrm.utils import cache
|
|
|
|
|
|
register = template.Library()
|
|
|
|
|
|
@register.filter(name="rating")
|
|
def get_rating(book, user):
|
|
"""get the overall rating of a book"""
|
|
return cache.get_or_set(
|
|
f"book-rating-{book.parent_work.id}",
|
|
lambda u, b: models.Review.objects.filter(
|
|
book__parent_work__editions=b, rating__gt=0
|
|
).aggregate(Avg("rating"))["rating__avg"]
|
|
or 0,
|
|
user,
|
|
book,
|
|
timeout=15552000,
|
|
)
|
|
|
|
|
|
@register.filter(name="user_rating")
|
|
def get_user_rating(book, user):
|
|
"""get a user's rating of a book"""
|
|
rating = (
|
|
models.Review.objects.filter(
|
|
user=user,
|
|
book=book,
|
|
rating__isnull=False,
|
|
deleted=False,
|
|
)
|
|
.order_by("-published_date")
|
|
.first()
|
|
)
|
|
if rating:
|
|
return rating.rating
|
|
return 0
|