django执行迁移失败问题

问题描述:

第一次执行迁移成功且数据库生成了表,接着,我把pycharm中的迁移文件、数据库表直接删掉,重新执行迁移,发现失败,日志如下:

Running migrations:
  No migrations to apply.

(venv) D:\360MoveData\Users\lenovo\Desktop\django_auto_test>python manage.py makemigrations study
Migrations for 'study':
  study\migrations\0001_initial.py
    - Create model AllField

(venv) D:\360MoveData\Users\lenovo\Desktop\django_auto_test>python manage.py migrate
Operations to perform:
  Apply all migrations: admin, auth, contenttypes, polls, sessions, study
Running migrations:
  No migrations to apply.

很显然,生成迁移文件是成功的,但是没能成功执行迁移,原因是没被应用到数据库。

解决过程:

1、问题分析

(1)可能是django认为迁移文件与之前相同而没有执行

(2)可能是翻译成的sql语句,不包含创建表的过程

(3)可能存在缓存问题

2、从最易执行的操作入手,用排除法尝试解决

(1)重启pycharm,并执行,未能解决,排除

(2)查看翻译成的sql语句,包含了创建表的过程,未能解决,排除

python manage.py sqlmigrate study 0001

翻译成sql语句如下:

BEGIN;
--
-- Create model AllField
--
CREATE TABLE "study_allfield" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "BigIntegerField001" bigint NOT NULL, "BinaryField001" BLOB NOT NULL, "Boo
leanField001" bool NOT NULL, "CharField001" varchar(10) NOT NULL, "DateField001" date NOT NULL, "DateTimeField001" datetime NOT NULL, "DecimalField001" de
cimal NOT NULL, "DurationField001" bigint NOT NULL, "EmailField001" varchar(254) NOT NULL, "FileField001" varchar(100) NOT NULL, "FilePathField001" varcha
r(100) NOT NULL, "FloatField001" real NOT NULL, "GenericIPAddressField001" char(39) NOT NULL, "ImageField001" varchar(100) NOT NULL, "IntegerField001" int
eger NOT NULL, "PositiveBigIntegerField001" bigint unsigned NOT NULL CHECK ("PositiveBigIntegerField001" >= 0), "PositiveIntegerField001" integer unsigned
 NOT NULL CHECK ("PositiveIntegerField001" >= 0), "PositiveSmallIntegerField001" smallint unsigned NOT NULL CHECK ("PositiveSmallIntegerField001" >= 0), "
SlugField001" varchar(50) NOT NULL, "SmallIntegerField001" smallint NOT NULL, "TextField001" text NOT NULL, "TimeField001" time NOT NULL, "URLField001" va
rchar(200) NOT NULL, "UUIDField001" char(32) NOT NULL);
CREATE INDEX "study_allfield_SlugField001_8c0c6e08" ON "study_allfield" ("SlugField001");
COMMIT;

(3)django认为迁移文件与之前相同而没有执行,这个。。。不好解决

想一下,django发出了迁移文件的请求,经过了数据库,返回了No migrations to apply.

对于django来说,执行的迁移记录会记录在数据库的表中,如果名称一致,将不会执行。

考虑到本地删除了迁移文件,重新生成的迁移文件又是从001开始,相同迁移记录不执行的概率很大,于是检查数据库的相关表如下:

django执行迁移失败问题

尝试删除该记录再重新执行迁移,发现执行成功(解决问题后,反而感觉索然无味了,没意思):

 django执行迁移失败问题

 

上一篇:OKR到底什么?看完你就懂了


下一篇:django migration No migrations to apply