아래의 명령어를 사용하여 쉘에 진입하여 API를 사용해봅시다.
$ python manage.py shell
from polls.models import Choice, Question # 작성했던 모델들을 import 합니다. >> Question.objects.all() #<QuerySet []> >> from django.utils import timezone # timezone 을 사용하기 위하여 import >> q = Question(question_text="What is new?", pub_date=timezone.now()) # q라는 변수에 해당 데이터를 넣습니다. >> q.save() # q 변수를 저장합니다. >> q.id # q의 id를 출력합니다. (django는 id를 자동 생성) >> q.question_text # q 변수의 question_text를 출력 >> q.pub_date # q 변수의 pub_date를 출력 >> q.question_text = " What is up?" #q 변수의 question_text 내용 수정 >> q.save() # q 변수의 데이터를 저장 >> Question.object.all() # <QuerySet [<Question: Question object (1)>]>
makemigrations 명령어를 자주 사용하게 될텐데, 해당 작업은 마이그레이션이라는 곳에 작성해놓은 모델들을 데이터베이스 테이블 내에 테이블을 만들 수 있도록 설계하는 작업입니다.
해당 명령어를 통하여 어떤 테이블을 만들어야할지 알 수 있습니다. (마이그레이션 파일 생성)$ python manage.py makemigrations polls //Migrations for 'polls': polls/migrations/0001_initial.py - Create model Question # Question model의 테이블 생성 - Create model Choice # Choice model의 테이블 생성
showmigrations mysite[app이름] 명렁어는 DB에 적용되었는지 확인할 수 있습니다.
$ python manage.py showmigrations polls // [X] 0001_initial -->
sqlmigrate 명령어는 생성된 migrations 파일들이 어떤 sql 문장을 실행하는지 보여줍니다.
$ python manage.py sqlmigrate polls 0001 //BEGIN; -- -- Create model Question -- CREATE TABLE "polls_question" ( # polls_question table 생성 "id" serial NOT NULL PRIMARY KEY, "question_text" varchar(200) NOT NULL, "pub_date" timestamp with time zone NOT NULL ); -- -- Create model Choice -- CREATE TABLE "polls_choice" ( #polls_choice table 생성 "id" serial NOT NULL PRIMARY KEY, "choice_text" varchar(200) NOT NULL, "votes" integer NOT NULL, "question_id" integer NOT NULL ); ALTER TABLE "polls_choice" ADD CONSTRAINT "polls_choice_question_id_c5b4b260_fk_polls_question_id" FOREIGN KEY ("question_id") REFERENCES "polls_question" ("id") DEFERRABLE INITIALLY DEFERRED; CREATE INDEX "polls_choice_question_id_c5b4b260" ON "polls_choice" ("question_id"); COMMIT;
migrate 명령어는 migrations들의 파일 중 생성되지 않은 migrations들을 수집하여 테이블을 생성하여 데이터베이스의 스키마의 동기화가 이루어지게 해줍니다.
$ python manage.py sqlmigrate polls 0001 //Operations to perform: Apply all migrations: admin, auth, contenttypes, polls, sessions Running migrations: Rendering model states... DONE Applying polls.0001_initial... OK