I had a field on a model with was:
class SomeModel(models.Model):
some_field = models.CharField(max_length=10, null=True, blank=True)
Then I changed my model to:
class SomeModel(models.Model):
some_field = models.CharField(max_length=10, default='')
When I ran django-admin sqlmigrate somemodels somemigration
to check my migration I found the following changes:
ALTER TABLE "somemodels" ALTER COLUMN "some_field" SET DEFAULT '';
UPDATE "somemodels" SET "some_field" = '' WHERE "some_field" IS NULL;
ALTER TABLE "somemodels" ALTER COLUMN "some_field" SET NOT NULL;
ALTER TABLE "somemodels" ALTER COLUMN "some_field" DROP DEFAULT;
I am not understanding why the Django apply a DROP DEFAULT
in the table since I am creating a default value. If this is correct, how does Django implement the default values?
Information about my tools:
By default, the configuration uses SQLite. If you're new to databases, or you're just interested in trying Django, this is the easiest choice. SQLite is included in Python, so you won't need to install anything else to support your database.
Among these the best-suited database is PostgreSQL. Django supports PostgreSQL 9.5 and higher. psycopg2 2.5. 4 or higher is required, though the latest release is recommended.
From IDEA to Product Using Python / Django ORM stands for Object Relational Mapper. The main goal of ORM is to send data between a database and models in an application. It maps a relation between the database and a model. So, ORM maps object attributes to fields of a table.
The comments to django/db/backends/base/schema.py, starting ln. 571, detail the steps involved here:
When changing a column NULL constraint to NOT NULL with a given default value, we need to perform 4 steps:
- Add a default for new incoming writes
- Update existing NULL rows with new default
- Replace NULL constraint with NOT NULL
- Drop the default again.
Django does not usually use the built-in SQL default to set values (remember that Django can use callable values for defaults). You can find more information in this rejected bug report.
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