为什么Django makemigrations创建模型,将其重命名为model_old,再次创建并删除model_old?

时间:2016-07-11 16:51:35

标签: django django-migrations

创建一个只有少量CharField和ForeignKey的Django模型(使用Python 3.5 / Django 1.9.7 / SQLite)后,运行manage.py makemigrations我用manage.py sqlmigrate APP_NAME, MIGRATION_NAME分析了创建的SQL代码并得到了对结果感到惊讶。

任何人都可以解释为什么要创建,将表重命名为model_old,再次创建,将数据从创建/重命名的model_old导入刚刚创建的表,然后删除model_old表?

我看到最终结果看起来是正确的,我真正需要的表,我只是想了解它为什么这样做。 Bellow是生成的SQL脚本

BEGIN;
--
-- Create model Foo
--
CREATE TABLE "foo_foos" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "created" datetime NOT NULL, "modified" datetime NOT NULL, "name" varchar(250) NOT NULL, "description" varchar(250) NOT NULL,"bar_id" integer NULL REFERENCES "foo_bar" ("id"));
--
-- Alter unique_together for foos (1 constraint(s))
--
ALTER TABLE "foo_foos" RENAME TO "foo_foos__old";
CREATE TABLE "foo_foos" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "created" datetime NOT NULL, "modified" datetime NOT NULL, "name" varchar(250) NOT NULL, "description" varchar(250) NOT NULL,"bar_id" integer NULL REFERENCES "foo_bar" ("id"));;
INSERT INTO "foo_foos" ("created", "modified", "name", "description", "id", "bar_id") SELECT "created", "modified", "name", "description", "id", "bar_id" FROM "foo_foos__old";
DROP TABLE "foo_foos__old";
CREATE UNIQUE INDEX "foo_foos_name_42a88411_uniq" ON "foo_foos" ("name", "description");
CREATE INDEX "foo_foos_3b5ba656" ON "foo_foos" ("foo_id");

COMMIT;

这就是模型的样子:

class Foo(models.Model):
    name = models.CharField(max_lenght=250)
    description = models.CharField(max_lenght=250)
    bar = models.ForeignKey(Bar, on_delete=models.SET_NULL)

    class Meta:
        unique_together = ('name', 'description')

1 个答案:

答案 0 :(得分:0)

it's all about django emulation of SQLite, taken from the django official docs here's the explanation :

SQLite¶

SQLite has very little built-in schema alteration support, and so Django attempts to emulate it by:

Creating a new table with the new schema
Copying the data across
Dropping the old table
Renaming the new table to match the original name

This process generally works well, but it can be slow and occasionally buggy. It is not recommended that you run and migrate SQLite in a production environment unless you are very aware of the risks and its limitations; the support Django ships with is designed to allow developers to use SQLite on their local machines to develop less complex Django projects without the need for a full database