Caching Request Set

I am working on an application that requires me to filter through a large number of records. I read about QuerySets caching and related stuff and found some good stuff.

 qs = MyModel.objects.filter(Q(<initial_filter_to_narrow_down_size>)) 

After that, I want to put this qs in the cache for later use. I want to apply all other filters without getting into the database. sort of

 cache.set('qs', qs) 

but what happens when i do qs = qs.filter(q_object) ? Will the cache be changed? I do not want it. I want qs stay constant until I update it. What should I do in this case?

+4
source share
2 answers

.filter () clones the request before applying the filter. The cache will not be affected.

By the way, you can check out JohnnyCache ... a great query caching application.

0
source

What I understood from your question is that you just need to get a set of requests from the cache, as shown below.

 your_cached_qs = cache.get('qs') 

And then apply the filter you want.

 your_new_qs = your_cached_qs.filter(further_filter) 

This will not affect the request specified in the cache. Therefore, your cache will remain unchanged until you update it yourself, and your desired result is achieved.

0
source

Source: https://habr.com/ru/post/1437788/


All Articles