I created following test model. The model contains various fields which have default value.
class TestModel(models.Model):
name = models.CharField(max_length=32)
x = models.IntegerField(default=0)
y = models.IntegerField(default=1, null=True)
z = models.IntegerField(default=0, null=True, blank=True)
After that, I run migration command, and Django exported following migration code. As you can see, default values are filled using default parameters.
class Migration(migrations.Migration):
dependencies = [
]
operations = [
migrations.CreateModel(
name='TestModel',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('name', models.CharField(max_length=32)),
('x', models.IntegerField(default=0)),
('y', models.IntegerField(default=1, null=True)),
('z', models.IntegerField(default=0, null=True, blank=True)),
],
),
]
And finally, I got following MySQL code using Django's migration command.
BEGIN;
CREATE TABLE `base_testmodel` (
`id` integer AUTO_INCREMENT NOT NULL PRIMARY KEY,
`name` varchar(32) NOT NULL,
`x` integer NOT NULL,
`y` integer NULL,
`z` integer NULL
);
COMMIT;
Question: Although, I set default values as 1 and 0, It doesn't appear in SQL code. Is this a feature of Django? - or - What am I doing wrong?
When you set a default for a model field in Django, it isn't included in the SQL schema generated by Django.
As long as you create your model instances using the ORM, then this doesn't matter, as Django will set the default value. However, if you create model instances using raw SQL, then you do need to make sure you use the default value for the field if required.
There is a ticket 470 for adding default values to the SQL schema, but it has been closed as won't fix. Remember than default
can be a callable as well as a constant. It wouldn't be possible to add these callables as defaults to the SQL schema.
If you really require the default to be added to the SQL schema, you could run the alter table statement manually, or add it to a migration.
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