How to Integrate Redis in Django?

samiullahsaleem

Sami Ullah Saleem

Posted on February 6, 2023

How to Integrate Redis in Django?

Steps:
1.

pip install django-redis
Enter fullscreen mode Exit fullscreen mode
  1. 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",
        }
    }
}
Enter fullscreen mode Exit fullscreen mode
  1. 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
  2. Go to your view.py file and add these lines at the top
from django.core.cache import cache
Enter fullscreen mode Exit fullscreen mode
  1. 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
        })
Enter fullscreen mode Exit fullscreen mode
  1. 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.
💖 💪 🙅 🚩
samiullahsaleem
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.

Related