前言
使用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即可解决