Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django Cache (Redis) auto refresh when data is changed

Is there any way to notify django to refresh the cache if there were any changes made on the database related to the cache data ? I have found this post, there is no latest answer and the django version mentioned was 1.6. I looked into the cache documentation and haven't found anything that directly relates to the question.

My question is what if I cache a result of a database query and there are new records added in between the timeout for the cache

from django.core.cache import cache

results = MyModel.objects.all() # 4 count
cache.set('results', results ) # Cached for 5 mins

# Mean while records have been added to MyModel table

results = MyModel.objects.all() # 6 count
cache.get('results') # 4 count and would not be updated for 5 mins

Is there any way to check if there has been any addition to the database and the cache refresh whenever there has been addition or deletion of records from the database ?

I have close to 10 tables where this might be important. Where whenever a records has been changed, the cache has to be updated.

Any help or suggestions are much appreciated.

Project Stack:

Django: 1.9
Python: 3.5
Redis: 2.8 (Cache Database)
Postgres: 9.5 (Main Database)
like image 344
kt14 Avatar asked Sep 01 '16 19:09

kt14


People also ask

How do I refresh redis cache?

Clear Redis Cache With the redis-cli Command The easiest way to clear Redis cache is to use the redis-cli command. Databases in Redis are stored individually. Using the redis-cli command allows you to either clear the keys from all databases, or from a single specified database only.

Does Django automatically cache?

Local Memory Cache Unless we explicitly specify another caching method in our settings file, Django defaults to local memory caching. As its name implies, this method stores cached data in RAM on the machine where Django is running. Local memory caching is fast, responsive, and thread-safe.

How do I update redis cache in python?

You can run redis-cli -p <port_num> -n 1 and then flushdb in the new prompt and then exit . This will clear the redis cache and update the changes.


1 Answers

So after an Year, this is what I have came up with

We can register custom post_save register to the models in the app.py for each app where you want to update your cache or add the post_save listener for all the models while the project is initializing.

These two post's helped to come up with receiver function which will clear the cache for the redis key.

In my application I used "{}-{}-{}".format(slug, model_name, username) to as key to my redis key and I will delete this key every time the model data for that user is changed.

Here are the post I found helpful: Blog

like image 101
kt14 Avatar answered Oct 29 '22 13:10

kt14