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 5.x Django 4.2 Django 3.2