最近学习Python+Django 创建网站,遇到数据库不能同步问题, 总结如下
问题: 数据不能同步在你创建django models.py 或者 更改已存在的models.py, makemigrations
正常生成本地数据, 但是migrate不能同步数据库
(Q: database not updated when you ‘makemigrations’ for new models.py or add new field in
models.py)
错误提示信息: (Error Msg)
++ “No migrations to apply” 当你用 python manage.py migrate 命令
++ 或者‘django.db.utils.OperationalError: (1054, "Unknown column ...’ )当你点击网页
解决方案:(Solution)
++
Solution:
+ python manage.py inspectdb # check if related table/class in the DB?
+ python manage.py migrate --fake productApp zero # if not in the DB, run this command
# productApp is your app name
Operations to perform:
Unapply all migrations: productApp
Running migrations:
Rendering model states... DONE
Unapplying productApp.0001_initial... FAKED
+ python manage.py migrate <productApp> # migrate again
Operations to perform:
Apply all migrations: productApp
Running migrations:
Applying productApp.0001_initial... OK
+ # if related table in the DB, but still the same problem, need manually delete table from database with following steps:
+ install sqllite3 and update environment PATH for command usage.
+ py .\manage.py dbshell # loginto sqllite3
+ sqlite> .tables # list current table/class
+ sqlite> .schema productApp_product # check if related table field updated or not.
# productApp_product is your table name # which identified in your models.py
+ sqlite> DROP TABLE <productApp_product>; # remove/delete whole table, jump to #re-do with below 2 commands
'py .\manage.py makemigrations', and then ''
'py .\manage.py makemigrations productApp'