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.
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).
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.
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.
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() .
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With