4

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)

skysoft999
  • 540
  • 1
  • 6
  • 27

3 Answers3

4

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

skysoft999
  • 540
  • 1
  • 6
  • 27
0

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')
Deepanshu Mehta
  • 1,119
  • 12
  • 9
-1

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")
Vaibhav Mishra
  • 227
  • 2
  • 11
  • Hello @Vaibhav As per the django 3.0 doc from:: django.core.cache import caches > this import is recommended. and my query was about to use hset and hget, usual get and set are working fine here. – skysoft999 Mar 19 '20 at 05:41