angrykola

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

数据库配置完成后,就可以开始建立一个应用程序了,现在建立一个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;

还可以运行以下命令:

现在,再次运行 syncdb 命令在你的数据库中创建这些模型对应的表:

python manage.py syncdb

syncdb 命令会给在 INSTALLED_APPS 中有但数据库中没有对应表的应用执行 sqlall 操作。

现在,就可以进入 Python 的交互式 shell 中玩弄 Django 提供给你的 API 。要调用 Python sell ,使用如下命令:

python manage.py shell

 

posted on 2013-11-28 13:47  kolaman  阅读(250)  评论(0)    收藏  举报