Skip to content

Commit

Permalink
V2: Fixing stale/nonexisting objects.
Browse files Browse the repository at this point in the history
  • Loading branch information
EralpB committed May 17, 2020
1 parent f28e809 commit 508653a
Showing 1 changed file with 4 additions and 2 deletions.
6 changes: 4 additions & 2 deletions bookshop/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,18 +2,20 @@
from django.core.cache import cache
import time


class Author(models.Model):
name = models.CharField(max_length=255)

def get_top_books(self):
cache_key = 'Author:get_top_books:{}'.format(self.id)
cache_value = cache.get(cache_key)
if cache_value is not None:
return cache_value
return list(Book.objects.filter(id__in=cache_value))

time.sleep(5) # make the calculation slower for the sake of argument
books = list(Book.objects.order_by('-purchase_count')[:10])
cache.set(cache_key, books, 4 * 60 * 60) # cache for 4 hours
# cache.set(cache_key, books, 4 * 60 * 60) # cache for 4 hours
cache.set(cache_key, [book.id for book in books], 4 * 60 * 60) # cache for 4 hours
return books

def __str__(self):
Expand Down

0 comments on commit 508653a

Please sign in to comment.