【问题标题】:when to delete the cache entry in django何时删除 django 中的缓存条目
【发布时间】:2012-11-11 07:51:40
【问题描述】:

在我的 django 应用程序中,我有一个 BlogEntry 属于一个 Category。A BlogEntry 可能属于许多 Categorys

class BlogEntry(models.Model):
    creationdate=models.DateField(default=date.today)    
    description=models.TextField()
    author=models.ForeignKey(User,null=True)
    categories=models.ManyToManyField(Category)

class Category(models.Model):
    name=models.CharField(unique=True,max_length=50)
    description=models.TextField(blank=True)

用户可以编辑BlogEntry,并在此过程中删除它所在的Category

假设blogEntry1之前属于java,scala。如果用户对其进行编辑以删除scala。现在该条目只有一个类别,即java

在我的 list_view 中,我使用如下缓存

from django.core.cache import cache
def list_entries_on_day(request,year,month,day):
    ...
    key = 'entries_day'+'-'+year+'-'+month+'-'+day
    if key not in cache:
        entries = BlogEntry.objects.filter(...args..)
        cache.set(key,entries)
    entries_on_day =cache.get(key)
    ...

假设我今天创建了 2 个条目并将它们放入缓存中。如果我编辑其中一个 BlogEntys 并删除一个类别 即;

blogEntry1  has categories :java,scala
blogEntry2 has categories :dotnet,vbasic

最初我查询今天的条目并将结果放入缓存中

缓存现在有 [blogEntry1,blogEntry2] 对键 'entries_day-2012-11-11'

现在我编辑 blogEntry1 使其现在将 java 作为类别

,我需要从缓存中删除存储的条目吗?(因为缓存在修改之前包含BlogEntry对象)

【问题讨论】:

    标签: python django caching


    【解决方案1】:

    您可以通过为 model.save 注册一个信号处理程序来使缓存无效

    您还可以忍受这样一个事实,即用户在缓存到期之前会看到陈旧的内容(默认为 1 小时),请确保他登录的用户不会看到缓存的内容,否则他会鸣喇叭编辑丢失。

    嗯,我的回答有点含糊,但我只想说:不,您不必严格地在每次编辑时使缓存无效,这是性能和内容新鲜度之间的选择。

    还有一点:缓存使用的首选习惯用法是:

    entries_on_day = cache.get(key)
    if entries_on_day  is None:
        entries_on_day  = BlogEntry.objects.filter(...args..)
        cache.set(key,entries_on_day)
    

    你保存一个缓存查询

    【讨论】:

      猜你喜欢
      • 2012-09-16
      • 1970-01-01
      • 1970-01-01
      • 2014-08-18
      • 1970-01-01
      • 2010-10-17
      • 2011-06-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多