Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django model fields. Custom field value setter

Tags:

python

django

Is there any way to do in django custom property setter like this?

class MyModel(models.Model):
    myfield = models.CharField(length = 250)

    @myfield.setter
    def set_password(self, value):
       self.password = encrypt(value)
like image 589
Nikolay Fominyh Avatar asked Oct 27 '11 07:10

Nikolay Fominyh


People also ask

What is BigAutoField in Django?

BigAutoField is a 64-bit integer, much like an AutoField except that it is guaranteed to fit numbers from 1 to 9223372036854775807. One can create a BigAutoField using the following syntax, id = models.BigAutoField(primary_key=True, **options) This is an auto-incrementing primary key just like AutoField.

What is Max_length in Django?

max_length. Required. The maximum length (in characters) of the field. The max_length is enforced at the database level and in Django's validation using MaxLengthValidator .

What is On_delete in Django?

The on_delete method is used to tell Django what to do with model instances that depend on the model instance you delete. (e.g. a ForeignKey relationship). The on_delete=models. CASCADE tells Django to cascade the deleting effect i.e. continue deleting the dependent models as well.

What is the @property in Django?

Let's look at one example. In Python, @property is a built-in decorator that creates and returns a property object. The @property decorator is internally taking the bounded method as an argument and returns a descriptor object.


1 Answers

You will really set the value on saving the model, so it's better to override save() method (ot use pre_save signal).

like image 60
DrTyrsa Avatar answered Oct 05 '22 20:10

DrTyrsa