很多情况下,因为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 check
System 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即可。