Django加入缓存的查询集

时间:2016-02-23 23:30:32

标签: django django-rest-framework django-queryset django-cache

我有三种模式:

class Video(models.Model):
    video_pk = models.AutoField(primary_key=True)
    author_fk = models.ForeignKey(GRUser, related_name='uploaded_videos', db_column='author_fk')

class VideoLike(models.Model):
    video_like_pk = models.AutoField(primary_key=True)
    video_fk = models.ForeignKey(Video, related_name='likes_list', db_column='video_fk')
    author_fk = models.ForeignKey(GRUser, related_name='video_likes_list', db_column='author_fk')
    video_like_dttm = models.DateTimeField(auto_now_add=True)

class VideoStats(models.Model):
    video_fk_pk = models.OneToOneField(Video, primary_key=True, db_column='video_fk_pk', related_name='stats')
    likes_num = models.BigIntegerField(default=0)

为了防止相同的数据库命中,我会定期缓存一些热门视频:

from django.core.cache import cache

qs_all = models.Video.objects.select_related('author_fk', 'stats').filter(publication_status=models.Video.PUBLISHED).order_by('-stats__likes_num')

cache.set('popular_videos_all', qs_all[:length])

通过我的API(Django-Rest-Framework)返回这些视频时,我应该添加当前用户的video_like_pk,如果用户已经过身份验证等等。

我可以使用prefetch_related来完成它,但它会对数据库进行两次调用,而不会使用缓存的结果。我想从数据库中仅获取当前用户的VideoLikes,并从缓存中取出其余部分。可能吗?也许还有一种更好的其他方法?

0 个答案:

没有答案