Skip to content

Instantly share code, notes, and snippets.

@nmundar
Created February 3, 2014 23:11
Show Gist options
  • Save nmundar/8794346 to your computer and use it in GitHub Desktop.
Save nmundar/8794346 to your computer and use it in GitHub Desktop.
Django Singleton Model
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