Skip to content

Instantly share code, notes, and snippets.

@CrazyMath
Last active June 27, 2020 21:06
Show Gist options
  • Save CrazyMath/d4fc31bc09e8b0756569a416aede330b to your computer and use it in GitHub Desktop.
Save CrazyMath/d4fc31bc09e8b0756569a416aede330b to your computer and use it in GitHub Desktop.
Singleton Model
from django.db import models
from django.core.cache import cache
class SingletonModel(models.Model):
class Meta:
abstract = True
def delete(self, *args, **kwargs):
pass
def set_cache(self):
cache.set(self.__class__.__name__, self)
def save(self, *args, **kwargs):
self.pk = 1
super(SingletonModel, self).save(*args, **kwargs)
self.set_cache()
@classmethod
def load(cls):
if cache.get(self.__class__.__name__) is None:
obj, created = cls.objects.get_or_create(pk=1)
if not created:
obj.set_cache()
return cache.get(self.__class__.__name__)
@keglostephane
Copy link

keglostephane commented Jun 27, 2020

there is some typos in your snippet. I could be wrong but i think it should be:

if cache.get(cls.__class__.__name__) is None: instead of if cache.get(self.__class__.__name__) is None:
return cache.get(cls.__class__.__name__) instead of return cache.get(self.__class__.__name__)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment