为什么python迁移重命名表?

时间:2017-07-27 12:19:45

标签: python django

我是python django的新手...... 我正在创建这样的模型:

class Question(models.Model):
    question_text=models.CharField(max_length=200)
    pub_date=models.DateTimeField("DatePublished")

class Choice(models.Model):
    question=models.ForeignKey(Question,on_delete=models.CASCADE )
    choise_text=models.CharField(max_length=200)
    votes=models.IntegerField(default=0)

class Question(models.Model):
    question_text=models.CharField(max_length=200)
    pub_date=models.DateTimeField("DatePublished")

class Choice(models.Model):
    question=models.ForeignKey(Question,on_delete=models.CASCADE )
    choise_text=models.CharField(max_length=200)
    votes=models.IntegerField(default=0)

并在pycharm终端中运行这两个命令:

python manage.py makemigrations polls
python manage.py sqlmigrate polls 0001

然后我看到了一些像这样的输出:`BEGIN;

--
-- Create model Choice
--
CREATE TABLE "polls_choice" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "choise_text" varchar(200) NOT NULL, "votes" integer N
OT NULL);
--
-- Create model Question
--
CREATE TABLE "polls_question" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "question_text" varchar(200) NOT NULL, "pub_date" da
tetime NOT NULL);
--
-- Add field question to choice
--
ALTER TABLE "polls_choice" RENAME TO "polls_choice__old";
CREATE TABLE "polls_choice" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "choise_text" varchar(200) NOT NULL, "votes" integer N
OT NULL, "question_id" integer NOT NULL REFERENCES "polls_question" ("id"));
INSERT INTO "polls_choice" ("choise_text", "id", "question_id", "votes") SELECT "choise_text", "id", NULL, "votes" FROM "polls_choic
e__old";
DROP TABLE "polls_choice__old";
CREATE INDEX "polls_choice_7aa0f6ee" ON "polls_choice" ("question_id");
COMMIT;

`

就像你看到它将名为polls_choice的表重命名为polls_choice_old一样!但为什么? 这意味着可能在数据库中有一些同名的表!!好的,但为什么Django重命名了?有人可以告诉我,这个逻辑的原因是什么?

1 个答案:

答案 0 :(得分:1)

sqlite中的ALTER TABLE命令是有限的(more details here)。 Django通过重命名表,创建新表,复制数据,然后最终删除旧表来解决这个问题。