Django中文官方版03-配置数据库

来源:互联网 发布:网络电玩城加盟 编辑:程序博客网 时间:2024/05/16 17:19

:Django默认使用的是轻量数据库sqlite,如果不满足生产需求,可根据配置修改mysite/setting.py,DATABASES列表,支持主流数据库,当然写法有一定语法规定,可参照本文最下方地址

1.创建数据库

python manage.py migrate
2.创建models

打开polls/models.py文件,输入以下内容:

from django.db import modelsclass Question(models.Model):    question_text = models.CharField(max_length=200)    pub_date = models.DateTimeField('date published')class Choice(models.Model):    question = models.ForeignKey(Question, on_delete=models.CASCADE)    choice_text = models.CharField(max_length=200)    votes = models.IntegerField(default=0)
注:代码和一般其他web框架的orm意思差不多

3.激活modeles

打开mysite/settings.py文件,输入以下内容:

INSTALLED_APPS = [    'polls.apps.PollsConfig',    'django.contrib.admin',    'django.contrib.auth',    'django.contrib.contenttypes',    'django.contrib.sessions',    'django.contrib.messages',    'django.contrib.staticfiles',]
4.绑定app并通知系统models修改

python manage.py makemigrations polls
成功后,会出现以下内容:

Migrations for 'polls':  polls/migrations/0001_initial.py:    - Create model Choice    - Create model Question    - Add field question to choice
5.测试sql语句

python manage.py sqlmigrate polls 0001
注:0001为上面生成的目录/polls/migrations/0001_initial.py

成功后,输出以下内容:

BEGIN;---- Create model Choice--CREATE TABLE "polls_choice" (    "id" serial NOT NULL PRIMARY KEY,    "choice_text" varchar(200) NOT NULL,    "votes" integer NOT NULL);---- Create model Question--CREATE TABLE "polls_question" (    "id" serial NOT NULL PRIMARY KEY,    "question_text" varchar(200) NOT NULL,    "pub_date" timestamp with time zone NOT NULL);---- Add field question to choice--ALTER TABLE "polls_choice" ADD COLUMN "question_id" integer NOT NULL;ALTER TABLE "polls_choice" ALTER COLUMN "question_id" DROP DEFAULT;CREATE INDEX "polls_choice_7aa0f6ee" ON "polls_choice" ("question_id");ALTER TABLE "polls_choice"  ADD CONSTRAINT "polls_choice_question_id_246c99a640fbbd72_fk_polls_question_id"    FOREIGN KEY ("question_id")    REFERENCES "polls_question" ("id")    DEFERRABLE INITIALLY DEFERRED;COMMIT;
6.执行建表

python manage.py migrate
输出:

Operations to perform:  Apply all migrations: admin, auth, contenttypes, polls, sessionsRunning migrations:  Rendering model states... DONE  Applying polls.0001_initial... OK


原文摘自官方地址https://docs.djangoproject.com/en/1.11/intro/tutorial02/,本文只做精简化翻译,详细内容可去指定地址阅读