Created
February 3, 2014 23:11
-
-
Save nmundar/8794346 to your computer and use it in GitHub Desktop.
Django 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
class SingletonModel(models.Model): | |
""" | |
Singleton - Ensures there's always only one entry in the database, and can | |
fix the table (by deleting extra entries) even if added via another mechanism. | |
Has a static load() method which always returns the object - from | |
the database if possible, or a new empty (default) instance if the | |
database is still empty. | |
""" | |
class Meta: | |
abstract = True | |
def save(self, *args, **kwargs): | |
self.__class__.objects.exclude(id=self.id).delete() | |
super(SingletonModel, self).save(*args, **kwargs) | |
@classmethod | |
def load(cls): | |
try: | |
return cls.objects.get() | |
except cls.DoesNotExist: | |
return cls() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment