投票系统二

投票系统二:数据库的安装

在上一篇中 django实例:创建你的第一个应用投票系统(一) 已经介绍基本的功能,并已经启动服务了。这一节介绍数据库相关的东东
首先要安装数据库服务,并安装MySQL-python
yum install MySQL-python.x86_64 -y

设置数据库

首页打开mysite/settings.py
打开DATABASES
ENGINE:这个是要使用数据库的类型,如postgresql,sqlite,mysql等,如下设置
我使用的是mysql

DATABASES = {  
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'djangodb2',
        'USER':'root',
        'PASSWORD':'redhat',
        'HOST':'',
        'PORT':'',
    }
}

注意:要创建有数据库设置为utf8
create database djangodb2character set utf8;

设置应用和APP

找到INSTALLD_APP
在这里你看到的这些是django默认的应用

 'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.sites',
    'django.contrib.messages',
    'django.contrib.staticfiles',
     'django.contrib.admin',
     'django.contrib.admindocs',

下面再介绍一个命令syncdb
这个命令会根据安装 的app应用生成相应的数据库表结构,索引等信息
python manage.py syncdb
django1.7版本之后还需执行

python manage.py makemigrations
python manage.py migrate

执行完之后会看到在你设置的数据库中多了几张表,这些表就是django默认安装的应用生成的表

创建投票系统模型

下面先创建投票模型
django-admin.py startapp polls
打开polls/models.py文件,在里面写数据表信息

from django.utils import timezone
class Poll(models.Model):
        question=models.CharField(max_length=200)
        pub_date=models.DateTimeField('date published')
class Choice(models.Model):
        poll=models.ForeignKey(Poll)
        choice_text=models.CharField(max_length=200)
        votes=models.IntegerField(default=0)

里面包括两个class,每个class都是从django的models.Model继承的,class里面的CharField,DateTimeField等用来创建相应的字段类型。如
question=model. CharField(max_length=200)这个就代码创建字符类型的字段,最大长度为200
当然CharField,DateTimeField等都是从models.Field继承而来的。如果你想实现自己的数据类型列,也可以从model.Field继承,实现你特定的功能
第一个为投票项,设置了两个字段
question:输入问题的字段
pub_date:发布时间字段
第二个为选项,包括三个字段
poll:设置选项所对应的投票项
choice_text:选项文本
votes:投票数

现在我们把这个应用添加到setting.py的配置文件中

INSTALLED_APPS = (
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.sites',
    'django.contrib.messages',
    'django.contrib.staticfiles',
     'django.contrib.admin',
     'django.contrib.admindocs',
     'polls',
)

接着执行如下命令
python manage.py sql polls
你会看到在cmd窗口中会出现创建表的sql语句。执行这个命令仅仅是显示下django内部根据模型会怎样一步步来自动创建相应的表
现在我们再执行syncdb,这个时候级可以在数据库中看到poll表和choice表了
python manage.py syncdb
现在我们打开shell,在里面进行一些简单的常用的增,删,改查。
python manage.py shell

>>from  polls.models import Poll,Choice
获取Poll里面的数据,当然现在没有,所以是空的 
>> Poll.objects.all()
[]
添加一个投票,在这个引入了django里面的关于时间的一个模块
>>> from django.utils import timezone
>>> p=Poll(question="what's new?",pub_date=timezone.now())
>>> p.save()保存
>>> p.id()
Traceback (most recent call last):
  File "<console>", line 1, in <module>
TypeError: 'long' object is not callabl
查看生成之后的id及question和pub_date

>>> p.question
"what's new?"
>>> p.id
1L
>>> p.pub_date
datetime.datetime(2016, 7, 18, 5, 0, 39, 994624, tzinfo=<UTC>)
>>> p.question="what's up?"
>>> p.save()
>>> Poll.objects.all()
[<Poll: Poll object>]

在这个我们看到,输出的是<oll: Poll object>这个对象,我们相要的是直接的数据,所以在每个class里面给加上__unicode__() ,来输出相应的内容,其实就相当于c#、java里面的ToString()给重载下。

class Poll(models.Model):
	def __unicode__(self):
                return self.question
class Choice(models.Model):
	 def __unicode__(self):
                return self.choice_text

我们给Poll class增加一个新的方法

from django.db import models
import datetime
from django.utils import timezone
class Poll(models.Model):
        question=models.CharField(max_length=200)
        pub_date=models.DateTimeField('date published')
        def __unicode__(self):
                return self.question
        def was_published_recently(self):
                return self.pub_date >= timezone.now() - datetime.timedelta(days=1)

下面我们再操作一下

[root@yangguoqiang mysite]# python manage.py shell
Python 2.6.6 (r266:84292, Nov 22 2013, 12:16:22) 
[GCC 4.4.7 20120313 (Red Hat 4.4.7-4)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> from polls.models import Poll,Choice
>>> Poll.objects.all()
[<Poll: what's up?>]
>>> Poll.objects.filter(id=1)
[<Poll: what's up?>]
>>> Poll.objects.filter(question__startswith='What')
[<Poll: what's up?>]
根据发布时间来查找数据
>>> from django.utils import timezone
>>> current_year=timezone.now().year
>>> Poll.objects.get(pub_date__year=current_year)
<Poll: what's up?>
调用我们刚才添加的方法
>>> p=Poll.objects.get(pk=1)
>>> p.was_published_recently()
True

根据主键来查找数据
>>> p=Poll.objects.get(pk=1)
>>> p.choice_set.all()

创建三个选项
>>> p.choice_set.create(choice_text='Not much',votes=0)
<Choice: Not much>
>>> p.choice_set.create(choice_text='the sky',votes=0)
<Choice: the sky>
>>> c=p.choice_set.create(choice_text='just hacking again',votes=0)

访问投票项
>>> c.poll
<Poll: what's up?>
由poll对象来访问。他关联的选项的集合
>>> p.choice_set.all()
[<Choice: 22>, <Choice: not much>, <Choice: the sky>,  <Choice: just hacking again>
查询当前投票发布时间是今年的选项
>>> Choice.objects.filter(poll__pub_date__year=current_year)
[<Choice: 22>, <Choice: not much>, <Choice: the sky>, <Choice: just hacking again>
查找当前投票中以just hacking为开头的选项,并删除
>>> c=p.choice_set.filter(choice_text__startswith='just hacking')
>>> c.delete()
posted @ 2016-07-18 17:58  夏日花开  阅读(233)  评论(0编辑  收藏  举报