Django Admin:Django Admin中可以更改的变量/常量

时间:2017-08-22 09:21:24

标签: django django-admin

我想在Django Admin中拥有变量/常量,以后我可以在代码中使用。

例如API密钥,Google代码管理器标识号等

我知道我可以在设置或其他文件中设置它们,但这更适合营销团队,可以更改。

如何做到这一点?只是单个记录变量(不是多个 - 因此模型不是最佳解决方案)

1 个答案:

答案 0 :(得分:1)

然后执行以下操作:

class myConstant(models.Model)
    # ...

    def clean(self):
        if self.id: # instance already exists
            # do some clean
        elif myConstant.objects.count() > 0:
            raise ValidationError("Only one instance allowed")
        else:
            # do some clean

    def save(self):
        # check if this instance already exists
        if self.id:
           super().save()
        # else: count numbers of all instances of this model
        elif myConstant.objects.all().count() > 0:
            return # no save will be processed
        else:
            super().save()

这样,此模式只允许1个允许的实例 - 只能存在1个常量值的字段。

您可以进行更多保存,不仅可以检查当前实例是否已存在,还可以检查当前实例是否是您可能已有的实例。

if myConstant.objects.count() > 0 and myConstant.objects.all[0] == self:
    # do some clean in case of clean() method
    super().save() # in case of save method

此外,如果您想在应用程序/项目中的任何位置使用由模型表示的此常量,您只需在必要时向其他模型提供ForeignKeys。