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
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.
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