在这一节主要讲应用的创建和models设置,这里非常重要,一定要认真学习哦。
方法/步骤
-
创建app
D:\python\www\mysite>python3 manage.py startapp polls
应用polls的目录如下:
polls/
__init__.py
admin.py
migrations/
__init__.py
models.py
tests.py
views.py
-
编辑poll/models.py文件
from django.db import models
# Create your models here.
class Question(models.Model):
question_text = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
class Choice(models.Model):
question = models.ForeignKey(Question)
choice_text = models.CharField(max_length=200)
votes = models.IntegerField(default=0)
-
激活models
编辑mysite/settings.py,添加polls应用。
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'polls'
)
-
现在Django已经知道项目包括polls应用,运行如下命令:
D:\python\www\mysite>manage.py makemigrations polls
然后显示如下内容:
Migrations for 'polls':
0001_initial.py:
- Create model Choice
- Create model Question
- Add field question to choice
-
运行sqlmigrate命令可以返回SQL语句:
python3 manage.py sqlmigrate polls 0001
返回如下:
BEGIN;
CREATE TABLE "polls_choice" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "choice_text" varchar(200) NOT NULL, "votes" integer NOT NULL);
CREATE TABLE "polls_question" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT,
"question_text" varchar(200) NOT NULL, "pub_date" datetime NOT NULL);
CREATE TABLE "polls_choice__new" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "choice_text" varchar(200) NOT NULL, "votes" integer NOT NULL, "question_id"
integer NOT NULL REFERENCES "polls_question" ("id"));
INSERT INTO "polls_choice__new" ("id", "choice_text", "votes") SELECT "id", "cho
ice_text", "votes" FROM "polls_choice";
DROP TABLE "polls_choice";
ALTER TABLE "polls_choice__new" RENAME TO "polls_choice";
CREATE INDEX polls_choice_7aa0f6ee ON "polls_choice" ("question_id");
COMMIT;
-
现在运行migrate创建models表格。
python3 manage.py migrate
返回:
Operations to perform:
Apply all migrations: admin, auth, sessions, polls, contenttypes
Running migrations:
Applying polls.0001_initial... OK
927

被折叠的 条评论
为什么被折叠?



