Django default at database
Asked Answered
K

1

5

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!

Kansas answered 10/12, 2018 at 12:55 Comment(0)
C
7

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)

Cumulus answered 10/12, 2018 at 13:31 Comment(6)
Yes, this is huge architectural issue in Django.Remunerate
This is weird. Any idea why they did this?Darrondarrow
@SohamDongargaonkar, because is not trivial to translate random python code to any brand of database code (t-sql, pl-sql, ...)Cumulus
There's an accepted ticket for this in django with a good chance of making it to django 5.0 code.djangoproject.com/ticket/470Hols
wow @digenishjkl, keep us on the loop, please!Cumulus
This is now implemented in the development version of Django with the db_default keyword.Biotype

© 2022 - 2024 — McMap. All rights reserved.