Allow only one instance of a model in Django

后端 未结 7 1127
南笙
南笙 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:38

    I'm a bit late to the party but if you want to ensure that only one instance of an object is created, an alternative solution to modifying a models save() function would be to always specify an ID of 1 when creating an instance - that way, if an instance already exists, an integrity error will be raised. e.g.

    JuicerBaseSettings.objects.create(id=1)
    

    instead of:

    JuicerBaseSettings.objects.create()
    

    It's not as clean of a solution as modifying the save function but it still does the trick.

提交回复
热议问题