django(python manage.py imgrate)同步資料庫出錯後的解決辦法
很多情況下,因為app的models.py的檔案內容有誤,但是通過python manage.py check檢查不出來時,當執行python manage.py migrate同步資料庫時卻報錯,後續再修改models.py的內容,然後反覆執行python manage.py makemigrations和python manage.py migrate都會報錯。 本文針對此給出一種解決辦法:就是將執行python manage.py migrate同步資料庫前一次執行python manage.py makemigrations時生成的檔案及之後所有的檔案刪除即可,然後修改models.py,再執行makemigrations/migrate即可。
假設你的Project是MyStock,APP是stock,你的DB是mystock。
你的Project的目錄結構如下:
Mystock\__init__.py
\settings.py
\urls.py
\wsgi.py
stock\migrations\__init__.py
\0001_initial.py
\models.py
\views.py
\apps.py
\tests.py
\admin.py
\__init__.py
manage.py
MyStock/stock/models.py的內容如下:
class TestSelfDefinedTableName5(models.Model):
class Meta:
db_table = 'my_own_defined_table5'
資料庫中django_migrations 表的內容如下:
mysql> use mystock
Database changed
mysql> select name from django_migrations where app='stock'
+---------------------------------------+
| name |
+---------------------------------------+
| 0001_initial |
+---------------------------------------+
1 row in set (0.00 sec)
mysql>
現在修改models.py如下:
class TestSelfDefinedTableName5(models.Model):
class Meta:
db_table = 'my_own_defined_table5'
class TestSelfDefinedTableName6(models.Model):
class Meta:
db_table = 'my_own_defined_table5'
上面明顯的錯誤是會導致資料庫中有重複的表。
D:\030 Django_1\MyStock>python manage.py checkSystem check identified no issues (0 silenced).
D:\030 Django_1\MyStock>python manage.py makemigrations
Migrations for 'stock':
stock\migrations\0002_testselfdefinedtablename6.py:
- Create model TestSelfDefinedTableName6
注:執行python manage.py makemigrations之後,將生成stock\migrations\0002_testselfdefinedtablename6.py
D:\030 Django_1\MyStock>python manage.py migrate
.......
File "C:\Python27\lib\site-packages\MySQLdb\connections.py", line 36, in default error handler raise errorclass, error value django.db.utils.OperationalError: (1050, "Table 'my_own_defined_table5' already exists")
D:\030 Django_1\MyStock>
然後修改models.py,再執行:
D:\030 Django_1\MyStock>python manage.py makemigrations
Migrations for 'stock':
stock\migrations\0003_auto_20161011_2208.py:
- Rename table for testselfdefinedtablename6 to my_own_defined_table6
此時,將生成stock\migrations\0003_auto_20161011_2208.py
然後再同步資料庫:
D:\030 Django_1\MyStock>python
manage.py migrate
Operations to perform:
Apply all migrations: admin, auth, contenttypes, sessions, stock
Running migrations:
Applying stock.0002_testselfdefinedtablename6...Traceback
(most recent call la
st):
File "manage.py", line 22, in <module>
這時候還是報錯,原因是還是同步之前的0002****.py。
現在給出的解決辦法是:將執行python manage.py migrate同步資料庫前一次執行python manage.py makemigrations時生成的檔案及之後所有的檔案刪除即可,然後修改models.py,再執行makemigrations/migrate即可。即,刪除0002****.py,0003****.py,然後修改models.py,再執行makemigrations/migrate即可。