bookwyrm/bookwyrm/templatetags/landing_page_tags.py

85 lines
2.5 KiB
Python
Raw Normal View History

2021-03-08 16:49:10 +00:00
""" template filters """
2021-05-11 21:41:28 +00:00
from django import template
2022-01-08 19:43:56 +00:00
from django.db.models import Avg, StdDev, Count, F, Q
2020-01-29 23:10:32 +00:00
2021-10-06 17:37:09 +00:00
from bookwyrm import models
2020-02-21 23:39:25 +00:00
2020-01-29 23:10:32 +00:00
register = template.Library()
2021-03-08 16:49:10 +00:00
2022-01-08 19:43:56 +00:00
@register.simple_tag(takes_context=False)
def get_book_superlatives():
"""get book stats for the about page"""
total_ratings = models.Review.objects.filter(local=True, deleted=False).count()
data = {}
data["top_rated"] = (
models.Work.objects.annotate(
rating=Avg(
"editions__review__rating",
filter=Q(
editions__review__user__local=True, editions__review__deleted=False
),
2022-01-08 19:43:56 +00:00
),
rating_count=Count(
"editions__review",
filter=Q(
editions__review__user__local=True, editions__review__deleted=False
),
2022-01-08 19:43:56 +00:00
),
)
.annotate(weighted=F("rating") * F("rating_count") / total_ratings)
.filter(rating__gt=4, weighted__gt=0)
.order_by("-weighted")
.first()
)
data["controversial"] = (
models.Work.objects.annotate(
deviation=StdDev(
"editions__review__rating",
filter=Q(
editions__review__user__local=True, editions__review__deleted=False
),
2022-01-08 19:43:56 +00:00
),
rating_count=Count(
"editions__review",
filter=Q(
editions__review__user__local=True, editions__review__deleted=False
),
2022-01-08 19:43:56 +00:00
),
)
.annotate(weighted=F("deviation") * F("rating_count") / total_ratings)
.filter(weighted__gt=0)
.order_by("-weighted")
.first()
)
data["wanted"] = (
models.Work.objects.annotate(
shelf_count=Count(
"editions__shelves", filter=Q(editions__shelves__identifier="to-read")
)
)
.order_by("-shelf_count")
.first()
)
return data
2022-01-09 21:04:41 +00:00
@register.simple_tag(takes_context=False)
def get_landing_books():
"""list of books for the landing page"""
return list(
set(
models.Edition.objects.filter(
review__published_date__isnull=False,
review__deleted=False,
review__user__local=True,
review__privacy__in=["public", "unlisted"],
)
.exclude(cover__exact="")
.distinct()
.order_by("-review__published_date")[:6]
)
2021-03-08 16:49:10 +00:00
)