Last active
June 27, 2020 21:06
-
-
Save CrazyMath/d4fc31bc09e8b0756569a416aede330b to your computer and use it in GitHub Desktop.
Singleton Model
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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__) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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 ofif cache.get(self.__class__.__name__) is None:
return cache.get(cls.__class__.__name__)
instead ofreturn cache.get(self.__class__.__name__)