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

这样就可以创建表了。


点个赞呗~

相关推荐
程序员佳佳22 分钟前
2025年大模型终极横评:GPT-5.2、Banana Pro与DeepSeek V3.2实战硬核比拼(附统一接入方案)
服务器·数据库·人工智能·python·gpt·api
roo_11 小时前
github 获取构造图数据库的LNB数据集和使用说明
数据库
罗汉松驻扎的工作基地2 小时前
sql server 2014 下载和安装
数据库
l1t3 小时前
用docker安装oracle 19c
运维·数据库·docker·oracle·容器
Java&Develop3 小时前
DataEase图表页面传参至数据库查询方法 和页面筛选方法 sql传参
数据库·sql
+VX:Fegn08953 小时前
计算机毕业设计|基于springboot + vue作业管理系统(源码+数据库+文档)
数据库·vue.js·spring boot·后端·课程设计
luoluoal3 小时前
基于python的RSA算法的数字签名生成软件(源码+文档)
python·mysql·django·毕业设计
@zulnger3 小时前
Python 连接 MySQL 数据库_pymysql
数据库·python·mysql
别来无恙blwy3 小时前
SQL Server高可用自动故障转移失败(短时间内多次转移失败,只需一步可处理)
数据库·windows·sqlserver·负载均衡·可用性测试
gjc5924 小时前
MySQL 主从复制全解析:从基础原理到高级实战简介(附架构图)
数据库·mysql