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

这样就可以创建表了。


点个赞呗~

相关推荐
Hello.Reader5 分钟前
Redis 延迟排查与优化全攻略
数据库·redis·缓存
简佐义的博客1 小时前
破解非模式物种GO/KEGG注释难题
开发语言·数据库·后端·oracle·golang
爬山算法1 小时前
MySQL(116)如何监控负载均衡状态?
数据库·mysql·负载均衡
老纪的技术唠嗑局3 小时前
OceanBase PoC 经验总结(二)—— AP 业务
数据库
阿里云大数据AI技术4 小时前
OpenSearch 视频 RAG 实践
数据库·人工智能·llm
m0_623955666 小时前
Oracle使用SQL一次性向表中插入多行数据
数据库·sql·oracle
阿蒙Amon7 小时前
C#读写文件:多种方式详解
开发语言·数据库·c#
东窗西篱梦7 小时前
Redis集群部署指南:高可用与分布式实践
数据库·redis·分布式
就是有点傻8 小时前
C#如何实现中英文快速切换
数据库·c#
1024小神9 小时前
hono框架绑定cloudflare的d1数据库操作步骤
数据库