Allow only one instance of a model in Django
<p>I would like to control some configuration settings for my project using a database model. For example:</p>

<pre><code>class JuicerBaseSettings(models.Model):
    max_rpm = model.IntegerField(default=10)
    min_rpm = model.IntegerField(default=0)
</code></pre>

<p>There should only be one instance of this model:</p>

<pre><code>juicer_base = JuicerBaseSettings()
juicer_base.save()
</code></pre>

<p>Of course, if someone accidentally creates a new instances, it's not the end of the world. I could just do <code>JuicerBaseSettings.objects.all().first()</code>. However, is there a way to lock it down such that it's impossible to create more than 1 instance?</p>

<p>I found two related questions on SO. <a href="http://stackoverflow.com/questions/2273258/how-about-having-a-singletonmodel-in-django">This answer</a> suggests using 3rd party apps like <code>django-singletons</code>, which doesn't seem to be actively maintained (last update to the git repo is 5 years ago). <a href="http://stackoverflow.com/questions/4888159/django-models-only-permit-one-entry-in-a-model">Another answer</a> suggests using a combination of either permissions or <code>OneToOneField</code>. Both answers are from 2010-2011.</p>

<p>Given that Django has changed a lot since then, are there any standard ways to solve this problem? Or should I just use <code>.first()</code> and accept that there may be duplicates?</p>

<p>You can override <code>save</code> method to control number of instances:  </p>

<pre><code>class JuicerBaseSettings(models.Model):

    def save(self, *args, **kwargs):
        if JuicerBaseSettings.objects.exists() and not self.pk:
        # if you'll not check for self.pk 
        # then error will also raised in update of exists model
            raise ValidationError('There is can be only one JuicerBaseSettings instance')
        return super(JuicerBaseSettings, self).save(*args, **kwargs)
</code></pre>

python django