Allow only one instance of a model in Django

后端 未结 7 1140
南笙
南笙 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:35

    You can override save method to control number of instances:

    class JuicerBaseSettings(models.Model):
    
        def save(self, *args, **kwargs):
            if not self.pk and JuicerBaseSettings.objects.exists():
            # 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)
    

提交回复
热议问题