数据库配置完成后,就可以开始建立一个应用程序了,现在建立一个polls投票应用:
#进入manamge.py 文件目录下运行下代码 python manage.py startapp polls
之后就会创建一个子目录:
polls/
__init__.py
models.py
tests.py
views.py
在这简单的投票应用中,创建两个模型: Poll 和 Choice 。Poll 有问题和发布日期两个字段。Choice 有两个字段: 选项 ( choice ) 的文本内容和投票数。每一个 Choice 都与一个 Poll 关联。
现在开始编辑 polls/models.py 文件:
1 from django.db import models 2 3 # Create your models here. 4 class Poll(models.Model): 5 question = models.CharField(max_length=200) 6 pub_date = models.DateTimeField('date published') 7 def __unicode__(self): #python3中需要改成 __str__ 8 return self.question 9 10 class Choice(models.Model): 11 poll = models.ForeignKey(Poll) #将choice与poll进行关联 12 choice_text = models.CharField(max_length=200) 13 votes = models.IntegerField(default=0) 14 def __unicode__(self): 15 return self.choice_text
同时修改 settings.py 文件,在 INSTALLED_APPS 设置中加入 'polls' 字符。
INSTALLED_APPS = ( 'django.contrib.auth', ... ... # 'django.contrib.admindocs', 'polls', )
现在 Django 已经知道包含了 polls 应用,再运行如下命令:
python manage.py sql polls
将看到 有关投票应用的 CREATE TABLE SQL 语句 :
BEGIN; CREATE TABLE "polls_poll" ( "id" serial NOT NULL PRIMARY KEY, "question" varchar(200) NOT NULL, "pub_date" timestamp with time zone NOT NULL ); CREATE TABLE "polls_choice" ( "id" serial NOT NULL PRIMARY KEY, "poll_id" integer NOT NULL REFERENCES "polls_poll" ("id") DEFERRABLE INITIALLY DEFERRED, "choice_text" varchar(200) NOT NULL, "votes" integer NOT NULL ); COMMIT;
还可以运行以下命令:
- python manage.py validate – 检查在构建你的模型时是否有错误。
- python manage.py sqlcustom polls – 输出为应用定义的任何 custom SQL statements ( 例如表或约束的修改 ) 。
- python manage.py sqlclear polls – 根据存在于你的数据库中的表 (如果有的话) ,为应用输出必要的 DROP TABLE。
- python manage.py sqlindexes polls – 为应用输出 CREATE INDEX 语句。
- python manage.py sqlall polls – 输出所有 SQL 语句::djadmin:sql,sqlcustom, 和 sqlindexes 。
现在,再次运行 syncdb 命令在你的数据库中创建这些模型对应的表:
python manage.py syncdb
syncdb 命令会给在 INSTALLED_APPS 中有但数据库中没有对应表的应用执行 sqlall 操作。
现在,就可以进入 Python 的交互式 shell 中玩弄 Django 提供给你的 API 。要调用 Python sell ,使用如下命令:
python manage.py shell
浙公网安备 33010602011771号