Singleton models in Django

2013-02-25 by Senko Rašić

Sometimes it’s useful to have a database table with just one row. A typical example are user-editable settings – we want to store them with all the other data (in the database), but there’s really only one set of settings at any time.

This is easily done in Django by making sure we have only one database entry at model instance save. We can also go one step further and ensure we can always load the singleton object, even if that means creating a new (default) one in memory if the database is still empty.

Here’s a simple way of doing this (grab the complete source code here):

class SingletonModel(models.Model):
    class Meta:
        abstract = True

    def save(self, *args, **kwargs):
        super(SingletonModel, self).save(*args, **kwargs)

    def load(cls):
            return cls.objects.get()
        except cls.DoesNotExist:
            return cls()

That’s all there is to it. As a bonus, save() will clear out any additional database entries that might be there (for example, if the database was incorrectly modified by the code other than Django).

Not rocket science, but often comes in handy!

Senko Rašić
We’re small, experienced and passionate team of web developers, doing custom app development and web consulting.