Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Singleton Django Model
# Written by Senko Rasic <senko.rasic@goodcode.io>
# Released into Public Domain. Use it as you like.
from django.db import models
class SingletonModel(models.Model):
"""Singleton Django Model
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.
Also 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. If your instance has sane defaults (recommended),
you can use it immediately without worrying if it was saved to the
database or not.
Useful for things like system-wide user-editable settings.
"""
class Meta:
abstract = True
def save(self, *args, **kwargs):
"""
Save object to the database. Removes all other entries if there
are any.
"""
self.__class__.objects.exclude(id=self.id).delete()
super(SingletonModel, self).save(*args, **kwargs)
@classmethod
def load(cls):
"""
Load object from the database. Failing that, create a new empty
(default) instance of the object and return it (without saving it
to the database).
"""
try:
return cls.objects.get()
except cls.DoesNotExist:
return cls()
@Craiting

This comment has been minimized.

Copy link

@Craiting Craiting commented Jul 27, 2016

To retrieve the singleton object in the Django ORM would you just call SingletonModel.load() or SingletonModel() or SingletonModel.objects.load()?

@senko

This comment has been minimized.

Copy link
Owner Author

@senko senko commented Apr 6, 2017

@Craiting you’d call SingletonModel.load(), since it takes care of creating the object if it doesn’t exist. Equivalently, you could call SingletonModel.objects.get_or_create() and ignore the second returned value (whether it is a new one or not).

@Anjaan-g

This comment has been minimized.

Copy link

@Anjaan-g Anjaan-g commented Jan 6, 2021

Is this still supported by django?

@poudyalanil

This comment has been minimized.

Copy link

@poudyalanil poudyalanil commented May 10, 2021

Yes, it does support

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