gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 04:03:26 25 4
gpt4 key购买 nike

我有一个模型 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com