Django刪除表與重建表(Model)

前言

使用migrate同步數據到數據庫上時遇到了一些問題,記錄下來。比如設計表的時候,手賤直接刪除了一張表,然後就一直無法生成表了。
或者已經刪除了這張表,執行migrate時候,一直說"Table 'hello_xxx' already exists",都是血與淚的坑

手賤刪除表

如果有一天你手癢了,刪除了一張自己設計的表,你會發現,不管你怎麼執行makemigrations和migrate都無法自動生成新的表了。
就算你刪除app_name/migrations下面的0001_initial.py和其它文件,重新執行makemigrations和migrate依然無法查詢生成表,提示" No migrations to apply."
就算你重新改過models.py的標名稱,還是一樣的,不會自動創建。

解決辦法:
使用數據庫shell模式進入,cd到django的manage.py目錄,執行

python manage.py dbshell

如果出現CommandError: You appear not to have the 'mysql' program installed or on your path.說明mysql沒添加到環境變量,找到本地安裝的mysql的bin目錄。
如我本地的“D:\soft\mysql8013\mysql-8.0.11-winx64\bin”,添加到系統的環境變量Path下即可

執行delete from django_migrations where app='your_appname';

D:\web_djo\helloworld>python manage.py dbshell
mysql: [Warning] Using a password on the command line interface can be insecure.

Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 38
Server version: 8.0.11 MySQL Community Server - GPL

Copyright (c) 2000, 2018, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql> delete from django_migrations where app='hello';
Query OK, 1 row affected (0.24 sec)

mysql>

接着再執行makemigrations和migrate即可同步了

python manage.py makemigrations
python manage.py migrate

--fake

如果執行manage.py makemigrations 未提示錯誤信息,但manage.py migrate時進行同步數據庫時出現問題
出現這個報錯django.db.utils.OperationalError: (1050, "Table 'hello_xx' already exists"),解決辦法如下

python manage.py migrate app_name --fake

再執行python manage.py migrate即可解決

 

轉載自:https://www.wandouip.com/t5i155731/

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章