Reputation: 786
So as I recently came to understand, the default
that we specify in a Django field is merely for filling up pre-existing rows, and doesn't function as a "real" default value at the database level. This can be verified by looking up column_default
from the database shell.
If I understand correctly, default
is used by Postgres to put in values when there is no input. If that is so, then we shouldn't be able to create a new object in Django without providing the default value, right?
For ex -
class MyModel(models.Model):
name = models.CharField(max_length=255)
status = models.BooleanField(default=True) # new field added
For the above model, the default
is used for only backfilling the newly added field for pre-existing rows. It doesn't actually set a default at the database level.
column_name | column_default
-------------+----------------
mymodel |
But if that is so, I shouldn't be able to run this query -
MyModel.objects.create(name='test')
since there's no "real" default. But I can, and I don't understand why.
Thank you!
Upvotes: 5
Views: 2921
Reputation: 51705
Quoting docs:
The default value is used when new model instances are created and a value isn’t provided for the field. When the field is a primary key, the default is also used when the field is set to None.
Default works at application level, not at database level. I mean, when new model instance is created (in memory) default value is applied there is not an explicit value provided.
Default
is not translated to ddl ( database data definition language ) as not null
or unique
do.
Notice that default
may be a value or, alseo, may be a django function that is invoked when new model is created to provide a value.
Because all this, the default field value will not be present on database schema.
Edited 2023
Use the new db_default for database-computed default value (credits to @sytech, see comments)
Upvotes: 7