[ ] Django |
$ pip instal django-clever-cache
INSTALLED_APPS += ['clever_cache']
CACHES = {
"default": {
"BACKEND": 'clever_cache.backend.RedisCache',
"LOCATION": "redis://127.0.0.1:6379/1",
"OPTIONS": {
'DB': 1,
}
}
}
class Post(models.Model):
author = models.ForeignKey('auth.User')
title = models.CharField(max_length=128)
body = models.TextField()
created_at = models.DateTimeField(auto_now_add=True)
class Meta:
verbose_name = 'post'
verbose_name_plural = 'posts'
ordering = ['-created_at']
class Comment(models.Model):
author = models.ForeignKey('auth.User')
post = models.ForeignKey(Post, related_name='comments')
body = models.TextField()
created_at = models.DateTimeField(auto_now_add=True)
class Meta:
verbose_name = 'comment'
verbose_name_plural = 'comments'
ordering = ['-created_at']
class PostListView(ListView):
context_object_name = 'post_list'
def get_queryset(self):
post_list_qs = cache.get('post_list_qs')
if not post_list_qs:
post_list_qs = Post.objects.all().select_related(
'author'
).annotate(comments_count=Count('comments'))
cache.set(
'post_list_qs',
post_list_qs,
depends_on=[Post, Comment, User]
# Post, Comment User
)
return post_list_qs
class PostDetailView(DetailView):
model = Post
def get_context_data(self, **ctx):
post = self.get_post()
comments = self.get_comments(post)
ctx['post'] = post
ctx['comments'] = comments
return ctx
def get_post(self, *args, **kwargs):
pk = self.kwargs.get(self.pk_url_kwarg)
cache_key = "post_detail_%s" % pk
post = cache.get(cache_key)
if not post:
post = Post.objects.select_related('author').get(pk=pk)
cache.set(
cache_key, post,
depends_on=[post, post.author]
#
)
return post
def get_comments(self, post):
cache_key = "post_detail_%s_comments" % post.pk
comments = cache.get(cache_key)
if not comments:
comments = post.comments.all()
cache.set(
cache_key, comments,
depends_on=[post.comments]
# post.comments - RelatedManager,
# ,
)
return comments