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 could use a pre_save signal   </p>

<pre><code>@receiver(pre_save, sender=JuicerBaseSettings)
def check_no_conflicting_juicer(sender, instance, *args, **kwargs):
    # If another JuicerBaseSettings object exists a ValidationError will be raised
    if JuicerBaseSettings.objects.exclude(pk=instance.pk).exists():
        raise ValidationError('A JuiceBaseSettings object already exists')
</code></pre>

python django