python - Django:我需要制定缓存方法吗?

标签 python django caching django-models

我有一个模型 Person,我在其中执行大量相同类型的查询。例如,我可能会多次询问同一页面中的“个人资料图片”。

正如你在我的代码中看到的,我实现了一种缓存的“排序”:将结果放入一个数组中,然后,如果该数组中有一个键,则返回结果。

class Personne(BaseModel):

    def __init__(self, *args, **kwargs):
        # Mise en place de cache :
        self.cache = {}
        super(Personne, self).__init__(*args, **kwargs)

    def url_profile_picture(self):
        # gestion du cache :
        retour = self.cache.get('profile_picture')
        if retour:
            return retour
        a = PersonnePhoto.objects.filter(personne=self,
                                         photo_type=PersonnePhoto.PHOTO_PROFIL)
        if len(a):
            a = reverse('url_public', kwargs={'path': a[0].photo})
        else:
            a = staticfiles.static('img/no-picture-yet.png')
        self.cache['photo_profil'] = a
        return a

我想知道(因为我是 Django 新手)如果 Django 已经有自己的缓存系统是否有用。我的意思是:我的查询 PersonnePhoto.objects.filter(...) 会一直访问数据库 -> 我肯定需要自己的缓存,还是会被 Django 缓存 -> 无用编写自己的缓存方法?

最佳答案

from django.core.cache import cache

在你的模型中,我建议这样:

def url_profile_picture(self):
    # gestion du cache :
    retour = cache.get('profile_picture_%s' % self.pk)
    if retour:
        return retour

    else:
        a = PersonnePhoto.objects.filter(personne=self,
                                      photo_type=PersonnePhoto.PHOTO_PROFIL)
        if len(a):
            a = reverse('url_public', kwargs={'path': a[0].photo})
        else:
            a = staticfiles.static('img/no-picture-yet.png')

        cache.set('profile_picture_%s' % self.pk, a)

        return a

可以在这里阅读有关 django 缓存的更多信息:https://docs.djangoproject.com/en/1.9/topics/cache/

编辑:然后在您的个人资料区域中,您可以清除上传图像时的缓存,以使其显示速度更快。

关于python - Django:我需要制定缓存方法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36105504/

相关文章:

python - 在 Jython 中使用 OrderedDict

python - django admin 仅查看和编辑用户创建的内容

Django REST框架: How do you get the attributes from a serialized object?

c - 如何用C读取X86命中未命中缓存寄存器

css - 必须删除 Chrome 中的缓存才能查看我在 Wordpress 网站上所做的 css 更改。这可以自动处理吗?

python - 为什么在 4 核超线程 CPU 上使用 8 个线程比使用 4 个线程快?

python - Flask + Wsgi + Docker - 尚未安装用户加载程序

python - 成功安装PIL,也出现ImportError : cannot import name 'imread' from 'scipy.misc'

python - 重新显示时未显示初始数据的 Django ModelForm

http - URI 不透明和缓存公理