我想通过模型方法为模型字段提供默认值。
我该怎么做?
当我尝试这段代码时
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/