Skip to content

Instantly share code, notes, and snippets.

@cooncesean
Created May 31, 2013 22:19
Show Gist options
  • Save cooncesean/5688348 to your computer and use it in GitHub Desktop.
Save cooncesean/5688348 to your computer and use it in GitHub Desktop.
Template tag `get_franchise_gallery_items()` to get recent GalleryItems associated to a specific Category.
from django.core.cache import cache
from ella_galleries.models import GalleryItem
@register.assignment_tag
def get_franchise_gallery_items(category_tree_path, results=5):
"""
Takes a `category_tree_path`, an optional arg `results` and
returns a list of most recent GalleryItems in the Category.
Since this is an expensive query, we'll cache the results for
each category for 10 minutes.
Usage:
{% get_franchise_gallery_items 'this-i-know' as recent_gallery_items %}
{% for item in recent_gallery_items %}
{{ item }}
{% endfor %}
"""
# Check for the results in cache
key = 'get_franchise_gallery_items:%s' % category_tree_path
results = cache.get(key)
if results is not None:
return results
# Found nothing in cache, fetch the GalleryItems
results = GalleryItem.objects.filter(
gallery__listing__category__tree_path=category_tree_path
).order_by('-id')[0:results]
# Cache and return the results
cache.set(key, results, 60*10)
return results
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment