rationa1cuzz
V2EX  ›  Python

django 对于数据已存在数据的表增加非空字段如何处理?

By rationa1cuzz at 2021 年 1 月 13 日 · 2635 次点击
对于已经存在数据的表增加非空字段,makemigrations 会报错 You are trying to add a non-nullable field 'xx' to XXX without a default,有什么办法可以解决吗?还是说必须要给个默认值
5 条回复  •  2021-01-14 11:51:28 +08:00
wuwukai007
   1
wuwukai007  
   2021 年 1 月 13 日
null=True,blank=True
xpresslink
   2
xpresslink  
   2021 年 1 月 13 日
表增加非空字段必须要加 default:默认值,这可以是值或可调用对象。如果可调用,则每次创建新对象时都会调用它。
enomine
   3
enomine  
   2021 年 1 月 13 日
报错提示已经很明显了
从 MySQL 层面来讲,非空表加一列非空字段,如果没有设置默认值,那已经存在的那些数据新加这个字段应该填充什么数据呢?
IurNusRay
   4
IurNusRay  
   2021 年 1 月 14 日
要么设置 null=True,要么手动设置一个默认值,比如 0 或者""
msy45
   5
msy45  
   2021 年 1 月 14 日
如果不需要默认值,migrate 完再把默认值取消再 migrate 一次
推荐学习书目
› Learn Python the Hard Way
Python Sites
› PyPI - Python Package Index
› http://diveintopython.org/toc/index.html
› Pocoo
值得关注的项目
› PyPy
› Celery
› Jinja2
› Read the Docs
› gevent
› pyenv
› virtualenv
› Stackless Python
› Beautiful Soup
› 结巴中文分词
› Green Unicorn
› Sentry
› Shovel
› Pyflakes
› pytest
Python 编程
› pep8 Checker
Styles
› PEP 8
› Google Python Style Guide
› Code Style from The Hitchhiker's Guide
© 2026 V2EX · 36ms · 3.9.8.5