From 21bbdfc4b0f8a051c10abd33eaeeb3bfd7857626 Mon Sep 17 00:00:00 2001 From: q0w <43147888+q0w@users.noreply.github.com> Date: Fri, 20 Oct 2023 12:00:44 +0300 Subject: [PATCH] Make cache value serializable Convert model to dict by `model_to_dict`. Tested with django-redis using several backends: json, pickle. --- solo/models.py | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/solo/models.py b/solo/models.py index 692d044..cac876f 100644 --- a/solo/models.py +++ b/solo/models.py @@ -1,5 +1,6 @@ from django.conf import settings from django.db import models +from django.forms import model_to_dict try: from django.core.cache import caches @@ -41,7 +42,8 @@ def set_to_cache(self): cache = get_cache(cache_name) cache_key = self.get_cache_key() timeout = getattr(settings, 'SOLO_CACHE_TIMEOUT', solo_settings.SOLO_CACHE_TIMEOUT) - cache.set(cache_key, self, timeout) + cache_value = model_to_dict(self) + cache.set(cache_key, cache_value, timeout) @classmethod def get_cache_key(cls): @@ -56,8 +58,9 @@ def get_solo(cls): return obj cache = get_cache(cache_name) cache_key = cls.get_cache_key() - obj = cache.get(cache_key) - if not obj: + cache_value = cache.get(cache_key) + if not cache_value: obj, created = cls.objects.get_or_create(pk=cls.singleton_instance_id) obj.set_to_cache() - return obj + return obj + return cls(**cache_value)