Refactor caching logic
This commit is contained in:
parent
4c6109a1d6
commit
01dec1e140
7 changed files with 165 additions and 122 deletions
|
@ -11,6 +11,8 @@ from django.templatetags.static import static
|
|||
from django.urls import reverse
|
||||
from django.utils.text import slugify
|
||||
|
||||
from config.cache_durations import *
|
||||
from gallery.cache import cached_or_set
|
||||
from gallery.models.location import Location
|
||||
|
||||
|
||||
|
@ -27,25 +29,29 @@ class Album(models.Model):
|
|||
|
||||
@property
|
||||
def photos_in_album(self):
|
||||
"""
|
||||
Returns the number of photos in the album.
|
||||
Result is cached for PHOTO_COUNT_DURATION.
|
||||
"""
|
||||
key = self._cache_key('photo_count')
|
||||
count = cache.get(key)
|
||||
|
||||
if count is None:
|
||||
count = self.photos.count()
|
||||
cache.set(key, count, 60 * 10) # Cache 10 min
|
||||
|
||||
return count
|
||||
return cached_or_set(
|
||||
key,
|
||||
ALBUM_PHOTO_DURATION,
|
||||
lambda: self.photos.count()
|
||||
)
|
||||
|
||||
@property
|
||||
def photos_views(self):
|
||||
"""
|
||||
Returns the total number of views for all photos in the album.
|
||||
Result is cached for PHOTO_VIEWS_DURATION.
|
||||
"""
|
||||
key = self._cache_key('photo_views')
|
||||
views = cache.get(key)
|
||||
|
||||
if views is None:
|
||||
views = self.photos.aggregate(total_views=Sum('views'))['total_views'] or 0
|
||||
cache.set(key, views, 60 * 5) # Cache 5 min
|
||||
|
||||
return views
|
||||
return cached_or_set(
|
||||
key,
|
||||
ALBUM_PHOTO_VIEWS_DURATION,
|
||||
lambda: self.photos.aggregate(total_views=Sum('views'))['total_views'] or 0
|
||||
)
|
||||
|
||||
def save(self, *args, **kwargs):
|
||||
if not self.slug:
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue