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

这样就可以创建表了。


点个赞呗~

相关推荐
Codeking__13 小时前
Redis——value的数据类型与单线程工作模型
java·数据库·redis
rchmin13 小时前
MySQL主从复制原理详解
数据库·mysql
液态不合群14 小时前
Java中线程安全问题的原因和解决方案
java·数据库
程序员柒叔14 小时前
Dify 集成-数据库与缓存
数据库·缓存·dify
栗子叶14 小时前
深入理解 MySQL 半同步复制:AFTER_SYNC 为何能避免主从同步数据丢失?
数据库·mysql·adb·高可用·主从同步
我科绝伦(Huanhuan Zhou)14 小时前
MySQL主主复制管理器(MMM):技术原理与实践架构解析
数据库·mysql·架构
步步为营DotNet14 小时前
深度解析.NET 中IAsyncEnumerable:异步迭代的高效实现与应用】
服务器·数据库·.net
mpHH14 小时前
postgresql 执行器中readme的翻译
数据库·学习·postgresql
萧曵 丶14 小时前
覆盖索引与回表(MySQL 索引核心概念,性能优化关键)
数据库·mysql·性能优化·索引·聚簇索引