11

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.

yossi
  • 12,945
  • 28
  • 84
  • 110
  • Does the id have to be unique? person_id = models.AutoField(primary_key=True ) Just as an idea. – Don Jun 14 '13 at 20:57

2 Answers2

9

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)
Rohan
  • 52,392
  • 12
  • 90
  • 87
5

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.

yossi
  • 12,945
  • 28
  • 84
  • 110