Django model field default from model method

Deadly 提交于 2019-12-12 09:36:45

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!