Sami Ullah Saleem
Posted on February 6, 2023
Steps:
1.
pip install django-redis
- Go to settings and add these lines
CACHES = {
"default": {
"BACKEND": "django_redis.cache.RedisCache",
"LOCATION": "redis://127.0.0.1:6379/1", // Redis server running on your Machine
"OPTIONS": {
"CLIENT_CLASS": "django_redis.client.DefaultClient",
}
}
}
- For running redis server, istall msi from https://github.com/MicrosoftArchive/redis/releases Go to C drive then redis and then redis_cli Now, you have done setup
- Go to your view.py file and add these lines at the top
from django.core.cache import cache
- How it works?
def search(request):
query = request.GET.get('query', '')
if cache.get(query):
product = cache.get(query)
print("Cache hit")
else:
product = Product.objects.filter(Q(title__icontains=query)) | Product.objects.filter(Q(description__icontains=query))
cache.set(query, product)
print("Cache miss")
return render(request, 'store/search.html',{
'query':query,
'products':product
})
- In this code, first we get query and then check if query key is available in the cache or not. If available then get it's value and assign it to the product Else You have to get the product value based on the query from the database.
💖 💪 🙅 🚩
Sami Ullah Saleem
Posted on February 6, 2023
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.