Storing item views in Redis

Let's find a way to store the total number of times an image has been viewed. If we implement this using the Django ORM, it will involve an SQL UPDATE query every time an image is displayed. If we use Redis instead, we just need to increment a counter stored in memory, resulting in a much better performance and less overhead.

Edit the views.py file of the images application and add the following code to it after the existing import statements:

import redisfrom django.conf import settings# connect to redisr = redis.StrictRedis(host=settings.REDIS_HOST,                      port=settings.REDIS_PORT,                      db=settings.REDIS_DB)

With the preceding code, we establish the Redis connection in order to use it in our views. Edit the image_detail ...

Get Django 2 by Example now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.