Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django model field default from model method

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.

like image 289
yossi Avatar asked Aug 12 '12 15:08

yossi


People also ask

What is default in Django model?

default: The default value for the field. This can be a value or a callable object, in which case the object will be called every time a new record is created. null: If True , Django will store blank values as NULL in the database for fields where this is appropriate (a CharField will instead store an empty string).

What is __ Str__ in Django model?

The __str__ method just tells Django what to print when it needs to print out an instance of the any model. It is also what lets your admin panel, go from this. Note: how objects are just plainly numbered. to this.

How do I add a field to an existing model in Django?

To answer your question, with the new migration introduced in Django 1.7, in order to add a new field to a model you can simply add that field to your model and initialize migrations with ./manage.py makemigrations and then run ./manage.py migrate and the new field will be added to your DB. Save this answer.

How do you create an instance of a model from another model in Django?

To create a new instance of a model, instantiate it like any other Python class: class Model (**kwargs) The keyword arguments are the names of the fields you've defined on your model. Note that instantiating a model in no way touches your database; for that, you need to save() .


1 Answers

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)
like image 131
Rohan Avatar answered Oct 15 '22 15:10

Rohan