Django框架下的model管理makemigration & migrate

扶珂
2023-12-01

Django框架下使用model来操作数据对象。刚接触过程中,对makemigration 和 migrate有些不解,在此总结下。

makemigration生成ddl语句,migrate执行ddl语句。

详见如下例子。

(virtual) E:\virtual\myapp>python manage.py makemigrations
Did you rename person.firtst_name to person.first_name (a CharField)? [y/N] y
Migrations for 'app1':
  app1\migrations\0002_auto_20180530_2323.py
    - Create model Album
    - Create model Musician
    - Rename field firtst_name on person to first_name
    - Add field artist to album

(virtual) E:\virtual\myapp>python manage.py sqlmigrate app1 0002
BEGIN;
--
-- Create model Album
--
CREATE TABLE "app1_album" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "name" varchar(100) NOT NULL, "release_date" date NOT NULL, "num_stars" integer NOT NULL);
--
-- Create model Musician
--
CREATE TABLE "app1_musician" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "first_name" varchar(30) NOT NULL, "last_name" varchar(30) NOT NULL, "instrument" varchar(100) NOT NULL);
--
-- Rename field firtst_name on person to first_name
--
ALTER TABLE "app1_person" RENAME TO "app1_person__old";
CREATE TABLE "app1_person" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "last_name" varchar(30) NOT NULL, "birthday" datetime NOT NULL, "first_name" varchar(30) NOT NULL);
INSERT INTO "app1_person" ("id", "last_name", "birthday", "first_name") SELECT "id", "last_name", "birthday", "firtst_name" FROM "app1_person__old";
DROP TABLE "app1_person__old";
--
-- Add field artist to album
--
ALTER TABLE "app1_album" RENAME TO "app1_album__old";
CREATE TABLE "app1_album" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "name" varchar(100) NOT NULL, "release_date" date NOT NULL, "num_stars" integer NOT NULL, "artist_id" integer NOT NULL REFERENCES "app1_musician" ("id") DEFERRABLE INITIALLY DEFERRED);
INSERT INTO "app1_album" ("id", "name", "release_date", "num_stars", "artist_id") SELECT "id", "name", "release_date", "num_stars", NULL FROM "app1_album__old";
DROP TABLE "app1_album__old";
CREATE INDEX "app1_album_artist_id_aed0987a" ON "app1_album" ("artist_id");
COMMIT;

(virtual) E:\virtual\myapp>python manage.py migrate
Operations to perform:
  Apply all migrations: admin, app1, auth, contenttypes, sessions
Running migrations:
  Applying app1.0002_auto_20180530_2323... OK

(virtual) E:\virtual\myapp>
和git的管理方式很相近啊。
 类似资料: