Django 做migrations时出错,解决方案

在做migrations的时候,偶尔会出现出错。


在已有数据的表中新增字段时,会弹出下面的信息

运行这个命令时

python 复制代码
python manage.py makemigrations

Tracking file by folder pattern: migrations

It is impossible to add a non-nullable field 'example' to book without specifying a default. This is because 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 with a null value for this column)
  2. Quit and manually define a default value in models.py.
    Select an option:

解决方案:

选择1

之后会弹出

Please enter the default value as valid Python.

The datetime and django.utils.timezone modules are available, so it is possible to provide e.g. timezone.now as a value.

Type 'exit' to exit this prompt

输入, 必须加双引号

python 复制代码
"1"

migrate 无法生成表

运行这个命令时

python 复制代码
python manage.py migrate

会出现这种结果

python 复制代码
Operations to perform:
  Apply all migrations: admin, app01, auth, contenttypes, sessions
Running migrations:
  No migrations to apply.

出现无法生成表的原因是,去到 django_migrations 表里查看,就能知道之前已经创建了表。所以得在该表用sql语句来删除对应的app数据。

最后运行下面两个命令

python 复制代码
python manage.py makemigrations

python manage.py migrate

这样就可以创建表了。


点个赞呗~

相关推荐
阿猿收手吧!17 小时前
【MySQL】ORM与ODB:数据库编程技术大比拼
数据库·mysql
一只专注api接口开发的技术猿18 小时前
从原理到实现:淘宝商品详情 API 的数据结构与调用机制剖析
大数据·数据结构·数据库·架构
+VX:Fegn089518 小时前
计算机毕业设计|基于springboot + vue民宿平台管理系统(源码+数据库+文档)
java·数据库·vue.js·spring boot·后端·课程设计
怎么就重名了19 小时前
Kivy的属性系统
java·前端·数据库
编程饭碗20 小时前
【Spring全局异常处理 早抛晚捕】
java·数据库·spring
langsiming20 小时前
Redis底层实现
数据库·redis·缓存
Hello World呀21 小时前
Redis是AP的还是CP?
数据库·redis·缓存
皇族崛起1 天前
【视觉多模态】- 3D建模尝试 I (广场3D建模,失败)
数据库·人工智能·3d·性能优化
JavaLearnerZGQ1 天前
redis笔记大全
数据库·redis·笔记
资生算法程序员_畅想家_剑魔1 天前
Java常见技术分享-26-事务安全-锁机制-作用与分类
java·开发语言·数据库