2012-11-10 36 views
1

在我的Django應用程序,一個登錄的用戶可以創建一個Entry它具有以下屬性在Django使用高速緩存 - 如何創建密鑰

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) 

在我看來,用戶可以檢索所有Entry S代表特定日期

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') 
    ... 

現在,我需要使用cache這一點,而不是做一個數據庫的命中每次用戶希望看到我應該設置緩存鍵day.How的Entry個上市?我是否應該使用由username+creationdate組成的字符串作爲關鍵字?

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) 
    .... 

回答

2

是的,你有正確的想法。一般原則是,對於每個可能產生不同結果的查詢,您的緩存鍵都需要不同。在這裏,你的查詢只取決於creationdaterequest.user,只要這兩個都在密鑰中,那麼你就被設置了。

但是,您還需要確保爲該函數使用緩存生成的密鑰與Django部署其他部分使用的密鑰不同。所以你還應該包含某種名稱空間。例如,類似這樣的東西:

"per-day-entries-{0}-{1}".format(request.user.username, creationdate)