且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Django模型的默认值未出现在SQL中

更新时间:2023-01-30 10:41:19

在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.