Django模型的默认值未出现在SQL中 [英] Default value of Django's model doesn't appear in SQL

查看:152
本文介绍了Django模型的默认值未出现在SQL中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了以下测试模型.该模型包含具有 默认 值的各个字段.

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)

之后,我运行迁移命令,并且Django导出了以下迁移代码.如您所见,默认值是使用 default 参数填充的.

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)),
            ],
        ),
    ]

最后,我使用Django的migration命令遵循了MySQL代码.

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;

问题:尽管,我将默认值设置为1和0,但它不会出现在SQL代码中.这是Django的功能吗? -或-我在做什么错了?

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?

推荐答案

在Django中为模型字段设置默认值时,它不包含在Django生成的SQL模式中.

When you set a default for a model field in Django, it isn't included in the SQL schema generated by Django.

只要您使用ORM创建模型实例,那都没关系,因为Django会设置默认值.但是,如果使用原始SQL创建模型实例,则需要确保在需要时使用字段的默认值.

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.

有一个票470 用于向SQL模式添加默认值,但是关闭,因为无法修复.请记住,default既可以是可调用的,也可以是常量.无法将这些可调用项作为默认值添加到SQL模式.

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.

如果确实需要将默认值添加到SQL模式,则可以手动运行alter table语句,或将其添加到迁移中.

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.

这篇关于Django模型的默认值未出现在SQL中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆