skip to Main Content

I am using django 3.0.4 and python 3.6.9. I have to use hset operation to set some values in redis cache.

  • My try:
from django.core.cache import caches

cache.set(), cache.get() // these operation are working

But I am not able to use hset and hget operation using this library. There is no proper documentation about this in Django official docs.

Note: I have referred this (Not A copy)

3

Answers


  1. Chosen as BEST ANSWER

    This is how I resolved the issue:

    • pip install django-redis-cache (3rd party redis client)

    Settings.py:

    CACHES = {
        "default": {
            "BACKEND": "django_redis.cache.RedisCache",
            "LOCATION": "127.0.0.1:6379/1",
            "OPTIONS": {"CLIENT_CLASS": "django_redis.client.DefaultClient",},
        }
    }
    

    In views.py ::

    from django.core.cache import caches
    redis_cache=caches['default']
    redis_client=redis_cache.client.get_client()
    redis_client.hset('myhash','key1', 'value1')
    

    Hope this will help. Docs: Django-redis-cache


  2. Hey @Sanu Your importing line is wrong Please import cache not caches. I am surprised how are you running with “caches”.

    from django.core.cache import cache
    cache.set("Your key", "Your dict data") 
    cache.get("Your key")
    
    Login or Signup to reply.
  3. Simple:

    from django.core.cache import caches
    cache = caches[settings.CACHE_FROM_SETTINGS]
    

    To store in cache:

    cache.hset('hash', 'key1', 'value1')
    cache.hset('hash', 'key2', 'value2')
    

    To fetch. specific key from specific hash:

    cache.hget('hash', 'key1')
    

    To fetch all the keys for that hash, use:

    cache.hgetall('hash')
    

    hgetall return dict:

    {'key1': 'value1', 'key2': 'value2', ... }
    

    and to delete the hash set:

    cache.hdel(hash, 'key')
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search