zoukankan      html  css  js  c++  java
  • Django写的投票系统2(转)

    在上一篇中 django实例:创建你的第一个应用投票系统(一) 已经介绍基本的功能,并已经启动服务了。这一节介绍数据库相关的东东。

    首页打开mysite/settings.py配置文件,

    设置数据库
    打到DATABASES

    ENGINE:这个是所要使用的数据库类型,如 postgresql、sqlite、mysql等。如下设置:

    django.db.backends.mysql

    NAME:数据库的名称或者如果你使用的是sqlite的话就是sqlite的路径。 

    USER :数据库的用户名

    PASSWORD :数据库密码

    HOST:数据库地址

    设置应用APP
    找到INSTALLED_APPS
    在这里你看到的这些是django默认的应用

    django.contrib.auth – 用户认证应用
    django.contrib.contenttypes – 内容类型应用
    django.contrib.sessions – session管理应用
    django.contrib.sites – 管理多个站点的应用
    django.contrib.messages – 消息处理
    django.contrib.staticfiles – 静态文件应用

    下面再介绍一个命令:syncdb

    这个命令会根据安装的app应用生成相应的数据库表结构、索引等信息。执行方式如下:

    python manage.py syncdb

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

    创建投票系统模型
    下面先创建投票模型

    python manage.py startapp polls

    生成的目录结构如下:

    polls/
        __init__.py
        models.py
        tests.py
        views.py

    打开polls/models.py 文件,在里面写数据表信息。

    复制代码
    from django.db import models
    
    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 = models.CharField(max_length=200) 这个就代码创建字符类型的字段,最大长度为200

    当然CharField、DateTimeField等都是从models.Field继承而来的。如果你想实现自己的数据类型列,也可以从models.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',
        # Uncomment the next line to enable the admin:
        # 'django.contrib.admin',
        # Uncomment the next line to enable admin documentation:
        # 'django.contrib.admindocs',
        'polls',
    )
    复制代码

    接着执行如下命令:

    python manage.py sql polls

    你会看到在cmd命令窗口中会出现创建表的sql语句。执行这个命令仅仅是显示下 django内部根据模型会怎样一步步的来自动创建相应的表的。

    复制代码
    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;
    复制代码

    当然还有几个有关模型的sql命令

    python manage.py validate – Checks for any errors in the construction of your models.
    python manage.py sqlcustom polls – Outputs any custom SQL statements (such as table modifications or constraints) that are defined for the application.
    python manage.py sqlclear polls – Outputs the necessary DROP TABLE statements for this app, according to which tables already exist in your database (if any).
    python manage.py sqlindexes polls – Outputs the CREATE INDEX statements for this app.
    python manage.py sqlall polls – A combination of all the SQL from the sql, sqlcustom, and sqlindexes commands.

    现在我们再执行syncdb,这个时候就会在数据库中看到poll表和choice表了。

    python manage.py syncdb

    现在打开shell,在里面进行一些简单的常用的增、删、改、查。

    python manage.py shell
    复制代码
    >>> from polls.models import Poll, Choice   # Import the model classes we just wrote.
    
    # 获取Poll里面的数据,当然现在是没有的,所以为空
    >>> Poll.objects.all()
    []
    
    # 添加一个投票,在这个引入了django里面的关于时间的一个模块。
    >>> from django.utils import timezone
    >>> p = Poll(question="What's new?", pub_date=timezone.now())
    
    # 保存
    >>> p.save()
    
    # 看看保存之后生成的id及question和pub_date
    >>> p.id
    1
    >>> p.question
    "What's new?"
    >>> p.pub_date
    datetime.datetime(2012, 2, 26, 13, 0, 0, 775217, tzinfo=<UTC>)
    
    # 修改question,记得要保存
    >>> 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
    复制代码

    你可以看看__unicode__() 和  __str__()的区别

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

    复制代码
    import datetime
    from django.utils import timezone
    # ...
    class Poll(models.Model):
        # ...
        def was_published_recently(self):
            return self.pub_date >= timezone.now() - datetime.timedelta(days=1)
    复制代码

    下面我们再操作一下。

    复制代码
    >>> from polls.models import Poll, Choice
    
    # Make sure our __unicode__() addition worked.
    >>> 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?>
    
    # Request an ID that doesn't exist, this will raise an exception.
    >>> Poll.objects.get(id=2)
    Traceback (most recent call last):
        ...
    DoesNotExist: Poll matching query does not exist. Lookup parameters were {'id': 2}
    
    
    >>> Poll.objects.get(pk=1)
    <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: Not much>, <Choice: The sky>, <Choice: Just hacking again>]
    >>> p.choice_set.count()
    3
    
    # 查询投票项发布时间是今年的选项
    >>> Choice.objects.filter(poll__pub_date__year=current_year)
    [<Choice: Not much>, <Choice: The sky>, <Choice: Just hacking again>]
    
    # 查找当前投票中以Just hacking为开头的选项,并删除
    >>> c = p.choice_set.filter(choice_text__startswith='Just hacking')
    >>> c.delete()
    复制代码

    对数据库的访问基本就这些了

  • 相关阅读:
    Ubuntu18.04+CUDA+CUDNN+Pytorch环境配置
    VIM入门必读(转)
    简述C和C++的学习历程(转)
    队列
    排序实现
    十进制转二进制
    北邮1467二叉树题引起的思考
    计算机是如何启动的?
    c语言字符串操作实现
    北邮机试——huffman权值问题
  • 原文地址:https://www.cnblogs.com/wangjiyuan/p/djangozhuan2.html
Copyright © 2011-2022 走看看