Allow only one instance of a model in Django

后端 未结 7 1126
南笙
南笙 2020-12-06 00:57

I would like to control some configuration settings for my project using a database model. For example:

class JuicerBaseSettings(models.Model):
    max_rpm =         


        
7条回答
  •  一整个雨季
    2020-12-06 01:18

    You could use a pre_save signal

    @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')
    

提交回复
热议问题