Django orm model default设置但是在数据库中并没有展示

项目场景:

向模型中添加数据但是报错
django.db.utils.OperationalError: (1364, “Field ‘xxxx’ doesn’t have a default value”)


问题描述

代码中已经设置了models.IntegerField(verbose_name=‘xxx’, default=600)
但是还是报错


原因分析:

本地测试没问题线上就会出错

检查环境一致
最后发现是线上的uwsgi没有关闭重启成功所以一直是之前的错误

官方链接

default¶
Field.default¶
The default value for the field. This can be a value or a callable object. If callable it will be called every time a new object is created.

The default can’t be a mutable object (model instance, list, set, etc.), as a reference to the same instance of that object would be used as the default value in all new model instances. Instead, wrap the desired default in a callable. For example, if you want to specify a default dict for JSONField, use a function:

def contact_default():
return {“email”: “[email protected]”}

contact_info = JSONField(“ContactInfo”, default=contact_default)
lambdas can’t be used for field options like default because they can’t be serialized by migrations. See that documentation for other caveats.

For fields like ForeignKey that map to model instances, defaults should be the value of the field they reference (pk unless to_field is set) instead of model instances.

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.


解决方案:

kill -9 杀掉旧的uwsgi

总结

在模型中设置默认值,数据库中并不会设置,只会在你执行model的时候orm给你加上默认值,数据库中是没有设置默认值的,还有就是如果设置了default就不设置blank=True和null=True

你可能感兴趣的:(django,django,python,后端)