skip to Main Content
cache.set("determ_" + str(id), cache_object)

Am working with Django cache using Redis, these are sample of my cache keys


but i get challenge when i want to delete cache using some part of key like determ_, appr_hist_, appr_act_

How will manage to accomplish this ?

from django.core.cache import cache

class CacheManager:
    def delete_cache(self, prefixes = []):
        for pattern in prefixes:

        return True
CacheManager.delete_cache(['determ_','appr_hist_', 'det_appr','appr_act_','deter_sect_'])



  1. Chosen as BEST ANSWER

    Thank you so much @Guy Royse for the great inputs. I use the idea and build this method and now it work fine thought i will need to deal with my policies and performance

    import redis
    class CacheManager:
        def delete_cache(self, prefixes = []):
            redis_client = redis.from_url('redis://')
            keys = redis_client.scan_iter("fcrs_:1:*")
            for key in keys:
                for prefix in prefixes:
                    clear_key = str(key.decode('utf-8')).split(":")
                    if prefix in clear_key[2]:
                        print(f": Found keys for prefix '{prefix}':", str(key.decode('utf-8')))
            return True

  2. I can’t speak for Django, but Redis doesn’t have a patterned delete feature. The way this is typically done works but it not performant.

    It involves the use of the SCAN command to get all the keys that match a pattern. SCAN is an O(N) operation where N is the number of keys you have in Redis. Then, you issue an UNLINK on all of the fields. The UNLINK is variadic so you can pass in all the matching keys to it.

    The KEYS and DEL commands will work as well but are even less performant. KEYS blocks Redis while it runs and other clients then can’t use Redis. DEL blocks Redis until the memory is freed while UNLINK returns and then frees the memory.

    Not sure if you can get to any of these commands from Django, but I hope this helps.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top