django 删除表后恢复

搭建测试环境

首先我们先建立一个blog的project

django-admin startproject blog

在建立一个account的app

cd blog

python mange.py startapp account

这时可以看到 migrations 里面没有任何关于模型的程序

编写一个模型

class User(models.Model):
    username = models.CharField(max_length=20,unique=True)
    password = models.CharField(max_length=15)

在blog/settings.py中添加account app

生成迁移脚本

python mange.py makemigrations

生成数据库表项

python mange.py migrate

前期的django环境搭好了

.
|-- account
|   |-- admin.py
|   |-- admin.pyc
|   |-- apps.py
|   |-- __init__.py
|   |-- __init__.pyc
|   |-- migrations
|   |   |-- 0001_initial.py
|   |   |-- 0001_initial.pyc
|   |   |-- __init__.py
|   |   `-- __init__.pyc
|   |-- models.py
|   |-- models.pyc
|   |-- tests.py
|   `-- views.py
|-- blog
|   |-- __init__.py
|   |-- __init__.pyc
|   |-- settings.py
|   |-- settings.pyc
|   |-- urls.py
|   |-- urls.pyc
|   `-- wsgi.py
|-- db.sqlite3
`-- manage.py

准备删除数据库

sqlite3 db.sqlite

drop table account_user;

恢复步骤

方法一

  1. 删除account/migrations目录中模型迁移脚本,这里就是0001_initial.py,0001_initial.pyc
  2. 进入数据库,删除django_migrations中跟account相关的所有表项
    delete from django_migrations where app=”account”;
  3. 重新执行数据迁移操作
    python mange.py makemigrations
    python mange.py migrate

方法二

注释django中对应的Model

执行以下命令:

  1. python manage.py makemigrations
  2. python manage.py migrate –fake

去掉注释重新迁移

  1. python manage.py makemigrations
  2. python manage.py migrate

猜你喜欢

转载自blog.csdn.net/yrx0619/article/details/81387351