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/

  • 4
    点赞
  • 23
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值