Avoid server error when encountering broken edition

If an edition is missing its work, this change allows the page to still
load without a server error; this is important because otherwise the
book will break every page it appears on, including the feed page.
This commit is contained in:
Mouse Reeve 2023-07-17 06:55:49 -07:00
parent 107f5b38ca
commit fbb9d75cc8
2 changed files with 10 additions and 0 deletions

View file

@ -12,6 +12,10 @@ register = template.Library()
@register.filter(name="rating")
def get_rating(book, user):
"""get the overall rating of a book"""
# this shouldn't happen, but it CAN
if not book.parent_work:
return None
return cache.get_or_set(
f"book-rating-{book.parent_work.id}",
lambda u, b: models.Review.objects.filter(

View file

@ -71,6 +71,12 @@ class RatingTags(TestCase):
)
self.assertEqual(rating_tags.get_rating(self.book, self.local_user), 5)
def test_get_rating_broken_edition(self, *_):
"""Don't have a server error if an edition is missing a work"""
broken_book = models.Edition.objects.create(title="Test")
broken_book.parent_work = None
self.assertIsNone(rating_tags.get_rating(broken_book, self.local_user))
def test_get_user_rating(self, *_):
"""get a user's most recent rating of a book"""
with patch("bookwyrm.models.activitypub_mixin.broadcast_task.apply_async"):