find . -path "*migrations*" -name "*.py" -not -path "*__init__*" -exec rm {} \;
在使用django框架开发的过程当中,咱们不可避免的遇到models层的变动,就涉及到数据库表的变更,django给我提供了一个migration的工具来作这些数据库表的变动。python
若是不加appname,那么就是指全部包含migrations 目录的appnginx
# 基于当前的model 检测修改,建立迁移策略文件 python manage.py makemigrations <appname> # 执行迁移动做 python manage.py migrate
有时候若是models改动比较大,migrations会失败,这个时候有两种选择,手工去修改migrations文件,第二种是清除全部migrations,从新migratesql
经过报错信息加上SQL语句找到找到问题,而后具体问题具体分析,是修改数据库里面的数据,仍是修改migrations生成的脚本。shell
python manage.py migrate python manage.py sqlmigrate <appname> 0001
当处理模型修改的时候:数据库
若是模型包含一个不曾在数据库里创建的字段,Django会报出错信息。 当你第一次用Django的数据库API请求表中不存在的字段时会致使错误。django
Django不关心数据库表中是否存在未在模型中定义的列。json
Django不关心数据库中是否存在未被模型表示的table。app
在使用SQLite3数据库时, 由于SQLite3 不支持删除列操做,只有有限地 ALTER TABLE 支持,因此修改数据库列的操做被新建表而后select into newtable 代替,因此会存在更多问题框架
参考ide
http://www.tuicool.com/articles/yM3IVr
python manage.py makemigrations
You are trying to add a non-nullable field 'college' to majorproperty without a default; we can't do that (the database needs something to populate existing rows). Please select a fix: 1) Provide a one-off default now (will be set on all existing rows) 2) Quit, and let me add a default in models.py Select an option: 1 Please enter the default value now, as valid Python The datetime and django.utils.timezone modules are available, so you can do e.g. timezone.now() >>> 1
在migrate的时候提示你须要指定一个默认值,用以处理NULL的状况
清除全部app目录/migrations/下除__init__.py 文件以外的py文件
find . -path "*migrations*" -name "*.py" -not -path "*__init__*" -exec rm {} \;
当migrations愈来愈多的时候执行 makemigrations 和 migrate 就会愈来愈慢,能够考虑对其瘦身(减小migrations文件的数量)
python manage.py squashmigrations schools 0002
django 项目提供了一个导出的方法 python manage.py dumpdata, 不指定 appname 时默认为导出全部的app
python manage.py dumpdata [appname] > appname_data.json
数据导入,不须要指定 appname
python manage.py loaddata appname_data.json
优势:能够兼容各类支持的数据库,也就是说,之前用的是 SQLite3,能够导出后,用这种方法导入到 MySQL, PostgreSQL等数据库,反过来也能够。
缺点:数据量大的时候,速度相对较慢,表的关系比较复杂的时候能够导入不成功。