How to use Redis in Django to optimize Your Django Performance
Tags: python, django, redis, programming
Published: 2023-10-13 07:38:19

Hello Devs, In this Post we'll learn about Redis and Django, Redis and Django combination is awesome if your Api's are slow and not responding or your server is showing 502 error.

```
Post Link:- https://pythondjangogeek.com/django/how-to-use-redis-in-django-to-optimize-your-django/
Linkedin:- https://www.linkedin.com/in/shivamrohillaa/
Github Link:- https://github.com/ShivamRohilllaa/django-redis
```

## So, let's talk about Redis

Redis is fast and basically it's a storage system, which stores your data and set all the data in cache.
and then you can retrieve your data through the cache.

## How Redis Boosts Django Performance

we use Redis with Django, when our api's are slows down due to multiple database queries. then we use caching to store the data and access the data frequently, when your data is set in redis, you just have to call the cache function(I'll explain in code below), and that cache function returns the data without hit the database, it's a one time process, it hits the database while set the cache or when we store the data in cache. and that's how redis speed up the api's or django queries, and it reduce the database load, and it's fast.

## Using Redis with Django: A Step-by-Step Guide

So, now we'll learn how to use redis with django for optimization.
We'll test redis with 10k+ objects.

So, first of all download Redis:- 

```
Download Redis
Redis for 64-bit Windows from this GitHub page: https://github.com/MicrosoftArchive/redis/releases/download/win-3.0.504/Redis-x64-3.0.504.msi
```
and after installing this, Go to your installed directory and run the redis-cli

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5puejtjgdta8gk8jq377.png)


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5mx7r31qs2m3an742wvc.png)

and now we start our django project, I hope you guys know how to create a django project and django app.

Now, add redis configuration in django settings.py

```

CACHES = {
    'default': {
        'BACKEND': 'django_redis.cache.RedisCache',
        'LOCATION': 'redis://127.0.0.1:6379/1',  # Replace with your Redis server details
        'OPTIONS': {
            'CLIENT_CLASS': 'django_redis.client.DefaultClient',
        }
    }
}

```

now create a model in models.py file,

```
class Post(models.Model):
    title = models.CharField(max_length=250)
    description = models.TextField()

    def __str__(self):
        return self.title
```
and add some objects and run script for adding duplicate data in the model, now we write main logic for the redis for set the cache and get the cache,

```
from django.shortcuts import render
from post.models import Post
from django.core.cache import cache
from django.http import HttpResponse

# Create your views here.

def home(request):
    qs = Post.objects.all()
    context = {'qs':qs}
    return render(request, 'index.html', context)

def set_data_in_cache(request):
    # Retrieve the data you want to cache
    qs = Post.objects.all()

    # Set the data in the Redis cache
    cache.set('post_data_key', qs)

    return HttpResponse("Data has been set in the cache.")

def get_data_from_cache(request):
    # Get the data from the Redis cache
    cached_data = cache.get('post_data_key')
    print(cached_data, 'cached_data')

    if cached_data is not None:
        # If data is found in the cache, you can use it as needed
        return render(request, 'redis_data.html', {'qs': cached_data})
    else:
        # If data is not found in the cache, you may choose to retrieve it from the database
        qs = Post.objects.all()
        return render(request, 'index.html', {'qs': qs})

```

we use two function for set and get the cache in redis, and that's so simple and easy,

``
for set the cache we use:- cache.set('post_data_key')
for get the cache we use:- cache.get('post_data_key')
```

and we set the Post model data in redis cache key and then we fetch the data from the cache key which you set in redis, and there's one more thing and that is timeout, if you want to expire your cache key so you can add the timeout while setting the cache key, you can use timeout=20 or any number, and if you don't want to expire your key, then use timeout=None, so that's how we can optimize our django app with the use of Redis.


Thank You
Shivam Rohilla | Python Developer