Django模型字段默认来自模型方法 [英] Django model field default from model method
本文介绍了Django模型字段默认来自模型方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我该怎么做?
当我尝试此代码
类人(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 :没有定义名称'self'。
如果我删除'self'我得到'create_id'需要1个参数。
解决方案
我最终这样做:(从两者中移除自己)
Class Person(models.Model):
def create_id():
return os.urandom(12).encode('hex')
name = models。 CharField(max_length = 255)
id = models.CharField(max_length = 255,default = create_id)
它正在工作,但我不知道这是否是最好的或正确的方式。
I want to give a model field default value from the a model method.
How can i do that ?
when i try this code
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)
I get NameError: name 'self' is not defined.
If i remove the 'self' i get that 'create_id' needs 1 parameter.
解决方案
I ended up doing this: (removing the self from both)
Class Person(models.Model):
def create_id():
return os.urandom(12).encode('hex')
name = models.CharField(max_length = 255)
id = models.CharField(max_length = 255,default = create_id)
it is working, but i am not sure if this is the best or the right way.
这篇关于Django模型字段默认来自模型方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文