1. 程式人生 > >model修改欄位出錯問題解決

model修改欄位出錯問題解決

起因

修改了表結構以後執行python3 manage.py migrate 報錯:

django.db.utils.OperationalError: (1091, "Can't DROP 'email'; check that column/key exists")
  • 1

所以進資料庫把對應的表刪除了,想著重新生成這張表. 
刪除表以後執行:

python3 manage.py makemigrations
python3 manage.py migrate
  • 1
  • 2

還是不能生成表,提示:No changes detected

處理過程

首先刪除了app對應目錄下的資料庫對應的檔案和快取檔案:

$ rm -rf migrations/ __pycache__/
  • 1

重新執行:

$ python3 manage.py makemigrations
No changes detected
$~/code/django/blogproject$ python3 manage.py makemigrations comments
Migrations for 'comments':
  comments/migrations/0001_initial.py
    - Create model Comment
$~/code/django/blogproject$ python3 manage.py migrate
Operations to perform:
  Apply all migrations: admin, auth, blog, comments, contenttypes, sessions, users
Running migrations:
  No migrations to apply.
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

進入資料庫發現仍然沒有生成表.

然後發現有一張django_migrations表,裡面記錄這有關建立表的記錄,刪除對應的資料表:

delete from django_migrations where app='yourappname';
  • 1

重新執行生成資料庫命令:

$ python3 manage.py makemigrations comments
No changes detected in app 'comments'
$~/code/django/blogproject$ python3 manage.py  migrate comments
Operations to perform:
  Apply all migrations: comments
Running migrations:
  Applying comments.0001_initial... OK
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

資料表順利生成.

結論

在執行 
python3 manage.py makemigrations 
python3 manage.py migrate 
操作的時候,不僅會建立0001_initial.py對應的模型指令碼,還會建立一個數據庫記錄建立的模型.如果想重新生成資料庫,需要兩個地方都做刪除.