How to specify default values in a Django model field?
Published on Aug. 22, 2023, 12:19 p.m.
To specify default values in a Django model field, you can use the default
attribute of the field definition. The default
attribute takes a value that will be assigned to the field if no value is provided.
Here’s an example of how to set a default value for a model field:
from django.db import models
class MyModel(models.Model):
my_field = models.CharField(max_length=100, default='default value')
In this example, we define a Model called MyModel
with a field called my_field
. The my_field
field is a CharField
with a max_length
of 100, and a default value of 'default value'
.
You can also set a callable as the default value if you want to compute a value for the field dynamically, like so:
from django.utils import timezone
from django.db import models
class MyModel(models.Model):
my_timestamp = models.DateTimeField(default=timezone.now)
In this example, we set the default value for the my_timestamp
field to be the current time, computed using the timezone.now()
function.
If you want the default value to be a callable and invoked on each call to the model’s constructor, then use the default
argument like the following example:
import uuid
from django.db import models
class MyModel(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
my_field = models.CharField(max_length=100, default='default value')
In this example, uuid4()
is a callable that generates a unique UUID value for each new model instance where primary_key=True
makes the id
field a primary key, which is why editable=False
is necessary since it should not be edited manually.
By setting default values, your code can handle instances where no values are provided for certain fields, and you can avoid having to manually specify values for every field on every new instance of the model.