Django: You are trying to add a non-nullable field stock without a default

本文详细解释了在Django项目中添加新字段后遇到的迁移错误,并提供了两种解决方案:为新字段提供默认值或将其设置为可空。文章强调了在非初始迁移中,为必填字段提供默认值的重要性,无论是否删除了现有数据库。
摘要由CSDN通过智能技术生成

I have added a new field in my model but after that I have deleted db.sqlite3 (to ensure I don't get error below)

agrawalo@:~/myapp> ls
README.md  config  core  manage.py  requirements.txt

 But still I get this error when I run makemigrations

# ./manage.py makemigrations
You are trying to add a non-nullable field 'high52' to stock without a default; we can't do that (the database needs something to populate existing rows).
Please select a fix:
 1) Provide a one-off default now (will be set on all existing rows with a null value for this column)
 2) Quit, and let me add a default in models.py

 

 

You can either provide a default value to the field

high52 = models.DecimalField(max_digits=19, decimal_places=2, default=0.0)

or you can make it optional

high52 = models.DecimalField(max_digits=19, decimal_places=2, null=True, blank=True)

You can make a decision based on your choice.

To answer your question about the error, the previously existing fields might have been created in the initial migration itself and they don't need a default value. But for the newly added field, you need a default value for mandatory fields and this default value will be populated in the existing records. This doesn't depend on whether you have deleted the existing database or not. This depends on the current state of migrations for that model. Since this is not the initial migration, you will need to provide a default value or make it optional.

 

 

[root@cnwbzp3137 aiaanzreport]# /home/shensh/snowreport/bin/python3 manage.py makemigrations
You are trying to add a non-nullable field 'prduedate' to pr without a default; we can't do that (the database needs something to populate existing rows).
Please select a fix:
 1) Provide a one-off default now (will be set on all existing rows with a null value for this column)
 2) Quit, and let me add a default in models.py
Select an option: 1
Please enter the default value now, as valid Python
The datetime and django.utils.timezone modules are available, so you can do e.g. timezone.now
Type 'exit' to exit this prompt
>>> Null
Invalid input: name 'Null' is not defined
>>> 'null'
Migrations for 'AIASSHK':
  AIASSHK/migrations/0003_pr_prduedate.py

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值