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): 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()
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!