在 Django 模板中,我有复合缓存键变量:
{% with video.id|to_str as video_id %}
{% with 'cm'|add:"video"|add:video_id as tmpl_key %}
{% cache 3600 * 24 tmpl_key %}
{% include 'comments/index.html' with obj=video %}
{% endcache %}
{% endwith %}
{% endwith %}
此 block 缓存视频页面上的评论。
On 信号(在添加新评论时发生)我正在尝试像这样使缓存无效:
@receiver(comment_was_posted)
def comment_was_posted_handler(sender, **kwargs):
comment = kwargs['comment']
cache_key = "cm" + str(comment.content_type) + str(comment.object_pk)
key = make_template_fragment_key(cache_key)
print(cache.get(key))
cache.delete(key)
print(cache.get(key)) - 始终返回 None(缓存失效失败,因为检索到的 key 没有任何缓存>),但我确信缓存工作正常并且 tmpl_key === cache_key 是相等的。
我是不是在使用 make_template_fragment_key 做错了什么?
请您参考如下方法:
无法将“复合缓存键”设置为串联字符串。 Django 模板引擎将时间部分后的下一个符号视为“缓存键”字符串。
在我的问题中是符号“*”:
{% cache 3600 * 24 tmpl_key %}
{% include 'comments/index.html' with obj=video %}
{% endcache %}
因此,django 将 '*' 视为缓存键,将 '24'、'tmpl_key' 视为 vary_on 参数。
正确代码:
你需要像这样传递缓存参数:
{% cache 3600 video_comments video.id %}
{% include 'comments/index.html' with obj=video %}
{% endcache %}
然后通过在 make_template_fragment_key 中传递 vary_on 参数列表来使缓存无效
@receiver(comment_was_posted)
def comment_was_posted_handler(sender, **kwargs):
comment = kwargs['comment']
if str(comment.content_type) == "video":
key = make_template_fragment_key('video_comments', [comment.object_pk])
