Django 可以工作之后,我们开始新建app。
A project can containmultiple apps. An app can be in multiple projects.
进入 mysite/ ,现在在与 manage.py 同级目录中(简单说,就是和manage.py在同一个文件夹。。。)
执行命令:
python manage.py startapp polls
命令成功执行之后,可以看见 polls 结构如下:
polls/ __init__.py admin.py migrations/ __init__.py models.py tests.py views.py在polls app 中,创建两个模块 Question 和 Choice , Question 中包含 “question” 和 ‘date’ ,Choice 中包含 “ choice” 和 “tally”(投票计数),并且 Question 是Choice 的外键。
编辑 polls/models.py 文件,代码如下:
import datetime from django.db import models from django.utils import timezoneclass Question(models.Model):
question_text = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')def __unicode__(self): return self.question_textclass Choice(models.Model):
question = models.ForeignKey(Question)
choice_text = models.CharField(max_length=200)
votes = models.IntegerField(default=0)模块编辑好了之后,激活模块,进行下面三步:def was_published_recently(self): return self.pub_date >= timezone.now() - datetime.timedelta(days=1)def __unicode__(self):return self.choice_text
1.告诉项目,现在多了一个名为“polls” 的app。
在 mysite/settings.py 中,修改以下部分:
INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'polls', #只是增加了这一点 )
现在,项目 mysite 已经知道 多了一个名为"polls" 的 app 了。
2.我们还要告诉它, "polls" 的一些具体的情况,比如说, polls 中存在两个模块。
执行以下命令:
python manage.py makemigrations polls
有以下输出则代表项目已经接受了 polls 的具体情况:
Migrations for 'polls': 0001_initial.py: - Create model Question - Create model Choice - Add field question to choice3. 增加了一个 app,就要创建相应的表(或者其他改变),用命令去执行相应的改变 。
python manage.py sqlmigrate polls 0001
出现类似以下的输出,则表示成功了:(不一定会一模一样)
BEGIN; CREATE TABLE polls_question ( "id" serial NOT NULL PRIMARY KEY, "question_text" varchar(200) NOT NULL, "pub_date" timestamp with time zone NOT NULL ); CREATE TABLE polls_choice ( "id" serial NOT NULL PRIMARY KEY, "question_id" integer NOT NULL, "choice_text" varchar(200) NOT NULL, "votes" integer NOT NULL ); 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;
4.我们知道了有这些改动,然后接下来,告诉数据库,有这样的变动。
命令:
python manage.py migrate
输出:(可能只会输出一部分,我觉得只要有最后那句 “Applying polls.0001_initial... OK”,就可以认为成功了)
Operations to perform: Synchronize unmigrated apps: sessions, admin, messages, auth, staticfiles, contenttypes Apply all migrations: polls Synchronizing apps without migrations: Creating tables... Installing custom SQL... Installing indexes... Installed 0 object(s) from 0 fixture(s) Running migrations: Applying polls.0001_initial... OK
现在 app 已经创建好并且和安装到项目之中了,接下来测试一下。
计进入 Python shell 交互环境。
命令:
python manage.py shell
出现 “>>>” 开始测试:
>>> from polls.models import Question, Choice>>> q = Question(question_text="What's new?", pub_date=timezone.now())>>> q.save()>>> q.id1>>> q.question_text"What's new?">>> q.pub_datedatetime.datetime(2012, 2, 26, 13, 0, 0, 775217, tzinfo=<UTC>)>>> q.question_text = "What's up?">>> q.save()>>> Question.objects.all()[<Question: Question object>]>>> Question.objects.all() [] >>> from django.utils import timezone>>> from polls.models import Question, Choice >>> Question.objects.all() [<Question: What's up?>] >>> Question.objects.filter(id=1) [<Question: What's up?>] >>> Question.objects.filter(question_text__startswith='What') [<Question: What's up?>] >>> from django.utils import timezone >>> current_year = timezone.now().year >>> Question.objects.get(pub_date__year=current_year) <Question: What's up?> >>> Question.objects.get(pk=1) <Question: What's up?> >>> q = Question.objects.get(pk=1) >>> q.was_published_recently() True >>> q = Question.objects.get(pk=1) >>> q.choice_set.all() [] # Create three choices. >>> q.choice_set.create(choice_text='Not much', votes=0) <Choice: Not much> >>> q.choice_set.create(choice_text='The sky', votes=0) <Choice: The sky> >>> c = q.choice_set.create(choice_text='Just hacking again', votes=0) >>> c.question <Question: What's up?> >>> q.choice_set.all() [<Choice: Not much>, <Choice: The sky>, <Choice: Just hacking again>] >>> q.choice_set.count() 3 >>> Choice.objects.filter(question__pub_date__year=current_year) [<Choice: Not much>, <Choice: The sky>, <Choice: Just hacking again>] >>> c = q.choice_set.filter(choice_text__startswith='Just hacking') >>> c.delete()源代码:https://github.com/Alkaid-seven/Django1.7_example_code