问题
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.
回答1:
You can define global method like this:
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)
回答2:
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.
来源:https://stackoverflow.com/questions/11923581/django-model-field-default-from-model-method