Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Automatically assigning model field values in Django

Is there a way to automatically set field values for models in Django when defining the model? This could be used for storing something like a timestamp (for example), but also for creating a field which is constructed as some function of the others.

In other words, I'm looking for something like this:

class Foo(models.Model):

spam = models.CharField(max_length=2000)
my_other_field = ###?

def generate_my_other_field():
    #Some algorithm to determine the value of my_other_field
like image 970
chimeracoder Avatar asked Feb 22 '26 21:02

chimeracoder


1 Answers

Yes, there is a way. From Django docs:

Field.default

The default value for the field. This can be a value or a callable object. If callable it will be called every time a new object is created.

like image 117
shanyu Avatar answered Feb 26 '26 00:02

shanyu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!