[Answered ]-Employing caching for the first page of a paginated view in Django

2👍

The following will attempt to check the cache if the page number is one. If it’s not found, a request will be made to the database.

page = request.GET.get('page', '1')
if page == '1':
    cached_page = cache.get('cached_page',None)
    if cached_page:
        return cached_page

#object_list has up to 1000 object ids at a time
paginator = Paginator(object_list, 20) #pass list of obj ids & no. of objs/page
try:
    page = paginator.page(page)
except PageNotAnInteger:
    # If page is not an integer, deliver first page.
    page = paginator.page(1)
except EmptyPage:
    # If page is out of range (e.g. 9999), deliver last page of results.
    page = paginator.page(paginator.num_pages)

page_contents = retrieve_posts(page.object_list) #retrieve 20 objects
if page == '1':
    cache.set('cached_page',page_contents)

It’s not clear what your queryset is like. But unless you have compelling evidence to show that this is a slow query, this is premature optimization. Retrieving items from the database using primary keys is very fast. Since you have to invalidate your cache twice per second, that overhead might make it not worth the effort.

👤e4c5

Leave a comment