python - Django 模型字段默认来自模型方法

标签 python django model default

我想通过模型方法为模型字段提供默认值。

我该怎么做?

当我尝试这段代码时

Class Person(models.Model):
    def create_id(self):
        return os.urandom(12).encode('hex')

    name = models.CharField(max_length = 255)
    id = models.CharField(max_length = 255,default = self.create_id)

我收到 NameError: name 'self' is not defined.

如果我删除“self”,我会得到“create_id”需要 1 个参数。

最佳答案

你可以这样定义全局方法:

def create_id():
    return os.urandom(12).encode('hex')

Class Person(models.Model):
   name = models.CharField(max_length = 255)
   id = models.CharField(max_length = 255,default = create_id)

关于python - Django 模型字段默认来自模型方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11923581/

相关文章:

python - np.correlate() 和 signal.fftconvolve() 给出了不同的答案

python - django 默认上下文变量

python - 进行子选择的 django 方法是什么?

python - Django 条件唯一在一起

python - 组织模式、源代码块、结果向量

python - 定义函数的全局行为?好的做法

c# - 如何将包含 IEnumerable 模型(复杂)的模型从 View C# MVC3 传递到 Controller ?

ruby-on-rails - rails : constraint violation on create but not on update

django - 应用标签覆盖较早的应用标签

django - 处理包含多行的 excel 文件时出现错误 502