2017-07-27 40 views
1

林在Python Django的只是新... 我創建一些模型是這樣的:爲什麼python遷移改名錶?

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_choicepolls_choice_old!但爲什麼? 這意味着也許有一些數據庫中的同名表!好的,但爲什麼Django重命名它?有人可以告訴我,這個邏輯是什麼原因?

+0

嘗試更改第二個問題和第二個選擇名稱...並重新運行 – PythonTester

回答

1

sqlite中的ALTER TABLE命令是有限的(more details here)。 Django通過重命名錶,創建新表,複製數據,然後最終刪除舊錶來解決這個問題。