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

这样就可以创建表了。


点个赞呗~

相关推荐
huahualaly8 小时前
重建oracle测试库步骤
数据库·oracle·ffmpeg
墨香幽梦客8 小时前
数据库选型对比:MySQL、Oracle与PostgreSQL的企业应用场景分析
数据库·mysql·oracle
wei_shuo8 小时前
多模一体破局:金仓数据库引领文档数据库国产化新征程
数据库·金仓数据库
Coder_Boy_9 小时前
基于SpringAI的在线考试系统-数据库 表结构 & 完整外键依赖关系梳理
java·数据库·人工智能·软件工程
清风拂山岗 明月照大江9 小时前
MySQL进阶
数据库·sql·mysql
努力进修9 小时前
金仓数据库:多模融合内核驱动,重构国产化文档数据库新生态
数据库·重构
Miss_Chenzr9 小时前
Springboot企业人事管理系统mi130(程序+源码+数据库+调试部署+开发环境)带论文文档1万字以上,文末可获取,系统界面在最后面。
java·数据库·spring boot
大猫会长9 小时前
postgresql内的RLS规则
数据库·postgresql
YIN_尹9 小时前
【MySQL】表的约束(上)
android·数据库·mysql
云和数据.ChenGuang9 小时前
运维故障之MySQL 连接授权错误
运维·数据库·人工智能·mysql