Iman Salehi
Iman Salehi

Reputation: 956

why python migration renamed tables?

Im just new in python django... i was creating some models like this:

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)

and ran this two commands in pycharm terminal:

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

then i saw some outputs like this:`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;

`

like you see it renamed table named polls_choice to polls_choice_old! but why? it means maybe there was some table by the same name in database !! Ok, but why Django renamed it? can somebody tell me, what is the reason for this logic?

Upvotes: 1

Views: 60

Answers (1)

Alasdair
Alasdair

Reputation: 308799

The ALTER TABLE command in sqlite is limited (more details here). Django gets around this by renaming the table, creating a new table, copying data across, and then finally deleting the old table.

Upvotes: 1

Related Questions