About Singleton Models

To limit a model only to a single instance, overwrite the full_clean() method:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
from django.db import models
from django.core.exceptions import ValidationError

class SiteSettings(models.Model):
    # … fields for the settings …

    def full_clean(self, *args, **kwargs):
        if self._state.adding and SiteSettings.objects.exists():
            raise ValidationError(
                "There can only be one SiteSettings instance."
            )
        return super().full_clean(*args, **kwargs)

Tips and Tricks Programming Django 4.x Django 3.2 Django 2.2 Django 1.11