在我的 django 应用程序中,登录用户可以创建一个Entry
具有以下属性的
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
它,而不是每次用户想在一天内查看Entry
s 列表时都进行数据库访问。我应该如何设置缓存的键?我应该使用由username+creationdate
as 键组成的字符串吗?
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)
....