在Django中仅允许一个模型实例 [英] Allow only one instance of a model in Django
问题描述
我想使用数据库模型来控制我的项目的一些配置设置。例如:
I would like to control some configuration settings for my project using a database model. For example:
class JuicerBaseSettings(models.Model):
max_rpm = model.IntegerField(default=10)
min_rpm = model.IntegerField(default=0)
应该只有一个实例模型:
There should only be one instance of this model:
juicer_base = JuicerBaseSettings()
juicer_base.save()
当然,如果有人不小心创建了一个新实例,那不是世界末日。我可以做 JuicerBaseSettings.objects.all()。first()
。但是,有没有一种方法可以锁定它,使得不可能创建多个实例?
Of course, if someone accidentally creates a new instances, it's not the end of the world. I could just do JuicerBaseSettings.objects.all().first()
. However, is there a way to lock it down such that it's impossible to create more than 1 instance?
我在SO上发现了两个相关的问题。 此答案建议使用诸如之类的第三方应用程序django-singletons
,似乎没有得到积极维护(最近一次git repo更新是5年前)。 另一个答案建议结合使用权限或 OneToOneField
。这两个答案都来自2010-2011年。
I found two related questions on SO. This answer suggests using 3rd party apps like django-singletons
, which doesn't seem to be actively maintained (last update to the git repo is 5 years ago). Another answer suggests using a combination of either permissions or OneToOneField
. Both answers are from 2010-2011.
鉴于Django从那时起发生了很大变化,是否有解决此问题的标准方法?还是我应该只使用 .first()
并接受可能存在重复项?
Given that Django has changed a lot since then, are there any standard ways to solve this problem? Or should I just use .first()
and accept that there may be duplicates?
推荐答案
您可以重写 save
方法来控制实例数:
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)
这篇关于在Django中仅允许一个模型实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!