1

In my django app, a logged in user can create an Entry which has the following attributes

from django.db import models
from datetime import date
from django.contrib.auth.models import User 
class Entry(models.Model):
    creationdate=models.DateField(default=date.today)
    description=models.TextField()
    author=models.ForeignKey(User,null=True)

In my view a user can retrieve all Entrys for a particular date as

def entries_on_ a_day(request,year,month,day):
    #month as 'jan','feb' etc
    ...
    entries_for_date = Entry.objects.filter(creationdate__year=year,creationdate__month=get_month_as_number(month),creationdate__day=day,author=request.user).order_by('-creationdate')
    ...

Now ,I need to use cache for this ,instead of doing a database hit everytime a user want to see a listing of Entrys on a day.How should I set the key for cache? Should I use a string made out of of username+creationdate as key?

from django.core.cache import cache

def entries_on_ a_day(request,year,month,day):
    creationdate=new date(year,get_month_as_number(month),day)
    key = request.user.username+ str(creationdate)
    if key not in cache:
        entries_for_date = Entry.objects.filter(creationdate__year=year,creationdate__month=get_month_as_number(month),creationdate__day=day,author=request.user).order_by('-creationdate')
        cache.set(key,entries_for_date)
    entries =  cache.get(key)
    ....

1 Answer 1

2

Yes, you have the right idea. The general principle is that your cache key needs to be different for each query that might produce different results. Here, your query does only depend on creationdate and request.user, so as long as both of those are in the key then you're set.

However, you also need to make sure that the keys you generate for this function's use of the cache are different from keys used by other parts of your Django deployment. So you should also include some kind of namespace. For example, something resembling this:

"per-day-entries-{0}-{1}".format(request.user.username, creationdate)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.