天天看點

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