天天看點

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連結着資料庫的話,進入資料庫,重新整理,新字段就添加成功了