django模型类生成数据表后,给数据表添加新的字段

django定义好模型生成数据表后,表格中的字段难免会根据需求发生更改,添加或者删除等

给数据表添加新的字段

1,首先给模型类添加新的属性
class User_Form(models.Model):
username = models.CharField(max_length=30,unique=True)
password = models.CharField(max_length=150)
email = models.CharField(max_length=79,unique=True)
uicon = models.ImageField(upload_to=“uploads/%y/%m/%d/”)
is_active = models.BooleanField(default=False)
is_delete = models.BooleanField(default=False)
uphone = models.CharField(max_length=11)-------->新添加的字段

def __str__(self):
    return self.username
    
class Meta:
    db_table = 'user_form'
    verbose_name = '用户注册信息表'
    verbose_name_plural = verbose_name

2,重新生成迁移文件
python manage.py makemigrations

3,出现两个选项,根据个人需求选择1或者2

[email protected]:~/myText$ python manage.py makemigrations

You are trying to add a non-nullable field ‘uphone’ to user_form 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------------>直接输入1或者2即可

4,选择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
》》》" "----------->注意,引号中间不能有空格,我是为了显示的清楚才空格的,另外引号必须是一对,我第一次输入双引号,就输入了一次,然后脑子短路,后一半没输,怕和我犯同样错误的话可以用单引号 ‘’ ,

5,回车,正常应该显示成功

》》》 “”
Migrations for ‘myApp’:
myApp/migrations/0002_user_form_uphone.py
- Add field uphone to user_form

6,然后执行迁移:python manage.py migrate,pycharm链接着数据库的话,进入数据库,刷新,新字段就添加成功了

猜你喜欢

转载自blog.csdn.net/zhige1112/article/details/85249291