zoukankan      html  css  js  c++  java
  • 开始你的第一个django_part1

    学习地址:官网

    全英文的,有点困难,现在是边看边写,最后把代码贴上来就可以了。

    想偷懒,想了下,还是算了,边学便翻译吧,不对的望大神指教了。

    我的操作环境win7+python2.7+django1.6

    安装django,这个配置网上一大片,百度一下就可了。

    先看下安装成功没有

    成功了的。

    先来创建一个项目,进入我们的django安装目录


     看见django-admin.py这个文件了吧,在dos下cd进这个目录。

    使用python django-admin.py startproject mysite创建一个mysite的项目

    目录结构会是下面这个样子的

    mysite/
        manage.py
        mysite/
            __init__.py
            settings.py
            urls.py
            wsgi.py
    

     使用  python manage.py runserver 命令运行开发服务器

     出现如下信息,表明成功了

    Validating models...
    
    0 errors found
    May 25, 2015 - 15:50:53
    Django version 1.6, using settings 'mysite.settings'
    Starting development server at http://127.0.0.1:8000/
    Quit the server with CONTROL-C.
    

     在浏览器输入上面那个http地址吧,it worked!

    端口默认是8000,可以使用 
    python manage.py runserver 8080 
    python manage.py runserver 0.0.0.0:8000  
    

     创建我们的应用,投票程序app,其实就是python的一个包而已

    使用 python manage.py startapp polls创建

    目录结构如下:

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

     一个投票程序,需要有问题和选项,一个选项有一个描述和一个投票数量

    在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)
    

     每个模块包含很多类,每个类就代表了一个数据库里面的表。

    poll这个类包含了问题和创建问题的时间,choice这个类包含了选项描述和票数,ForeignKey这个函数告诉Choice都关联单一一个Poll。其实也就是数据库之间的关系。

    激活我们的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',
    )
    

     把polls这个app加到我们的项目中。(注意,以后如果文件在这个项目中只有唯一一个,不给出路径了,比如settings.py这个文件,在这次学习的教程中,只有mysite目录下才会有)

    配置我们的数据库吧:python manage.py syncdb

    都是英文,但是能看懂吧,密码是要输入的哈。

    看看我们的数据库(使用的是默认的sqlite,网上下一个吧,要不然打不开这个文件奥)

    注意下图的箭头

    用shell来操作熟悉下数据库

    python manage.py shell
    
    C:Python27Libsite-packagesdjangoinmysite>python manage.py shell
    Python 2.7.9 (default, Dec 10 2014, 12:24:55) [MSC v.1500 32 bit (Intel)] on win
    32
    Type "help", "copyright", "credits" or "license" for more information.
    (InteractiveConsole)
    >>>
    

     看看Poll这个类里面有什么数据

    >>> from polls.models import Poll, Choice   # Import the model classes we just wrote.
    
    # No polls are in the system yet.
    >>> Poll.objects.all()
    []
    
    # Create a new Poll.
    # Support for time zones is enabled in the default settings file, so
    # Django expects a datetime with tzinfo for pub_date. Use timezone.now()
    # instead of datetime.datetime.now() and it will do the right thing.
    >>> from django.utils import timezone
    >>> p = Poll(question="What's new?", pub_date=timezone.now())
    
    # Save the object into the database. You have to call save() explicitly.
    >>> p.save()
    
    # Now it has an ID. Note that this might say "1L" instead of "1", depending
    # on which database you're using. That's no biggie; it just means your
    # database backend prefers to return integers as Python long integer
    # objects.
    >>> p.id
    1
    
    # Access database columns via Python attributes.
    >>> p.question
    "What's new?"
    >>> p.pub_date
    datetime.datetime(2012, 2, 26, 13, 0, 0, 775217, tzinfo=<UTC>)
    
    # Change values by changing the attributes, then calling save().
    >>> p.question = "What's up?"
    >>> p.save()
    
    # objects.all() displays all the polls in the database.
    >>> Poll.objects.all()
    [<Poll: Poll object>]
    

     注释的英文就自己翻译下。

    上面操作完成后,看看我们的数据库

    成功加入了。

    在使用Poll.objects.all()的时候输出的信息貌似没什么用,让我们改点东西

    在models.py文件里面

    class Poll(models.Model):
        question = models.CharField(max_length=200)
        pub_date = models.DateTimeField('date published')
    
        def __unicode__(self):
            return self.question
    
    class Choice(models.Model):
        poll = models.ForeignKey(Poll)
        choice_text = models.CharField(max_length=200)
        votes = models.IntegerField(default=0)
    
        def __unicode__(self):
            return self.choice_text
    

     在此运行,需要退出shell后(ctrl+z),在进。

    注意,unicode这个函数只能返回一个buffer或者string,tuple和list这种都不行奥。

    在使用Poll.objects.all()的时候输出就对了。

    让我们在poll里增加一个判断是否是最近发表的问题函数:

    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)
    
    class Choice(models.Model):
        poll = models.ForeignKey(Poll)
        choice_text = models.CharField(max_length=200)
        votes = models.IntegerField(default=0)
    
        def __unicode__(self):
            return self.choice_text
    

     问题:如何修改数据库信息呢。提供一个方法,根据primarykey来获取对象进行修改

    p = Poll.objects.get(pk=1)
    
    p.question #打印
    
    p.question = newstring #修改
    
    p.save() #记得保存
    

     下面的代码一步一步操作吧,注释自己翻译了

    >>> from polls.models import Poll, Choice
    
    # Make sure our __unicode__() addition worked.
    >>> Poll.objects.all()
    [<Poll: What's up?>]
    
    # Django provides a rich database lookup API that's entirely driven by
    # keyword arguments.
    >>> Poll.objects.filter(id=1)
    [<Poll: What's up?>]
    >>> Poll.objects.filter(question__startswith='What')
    [<Poll: What's up?>]
    
    # Get the poll that was published this year.
    >>> 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 by a primary key is the most common case, so Django provides a
    # shortcut for primary-key exact lookups.
    # The following is identical to Poll.objects.get(id=1).
    >>> Poll.objects.get(pk=1)
    <Poll: What's up?>
    
    # Make sure our custom method worked.
    >>> p = Poll.objects.get(pk=1)
    >>> p.was_published_recently()
    True
    
    # Give the Poll a couple of Choices. The create call constructs a new
    # Choice object, does the INSERT statement, adds the choice to the set
    # of available choices and returns the new Choice object. Django creates
    # a set to hold the "other side" of a ForeignKey relation
    # (e.g. a poll's choices) which can be accessed via the API.
    >>> p = Poll.objects.get(pk=1)
    
    # Display any choices from the related object set -- none so far.
    >>> p.choice_set.all()
    []
    
    # Create three choices.
    >>> 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)
    
    # Choice objects have API access to their related Poll objects.
    >>> c.poll
    <Poll: What's up?>
    
    # And vice versa: Poll objects get access to Choice objects.
    >>> p.choice_set.all()
    [<Choice: Not much>, <Choice: The sky>, <Choice: Just hacking again>]
    >>> p.choice_set.count()
    3
    
    # The API automatically follows relationships as far as you need.
    # Use double underscores to separate relationships.
    # This works as many levels deep as you want; there's no limit.
    # Find all Choices for any poll whose pub_date is in this year
    # (reusing the 'current_year' variable we created above).
    >>> Choice.objects.filter(poll__pub_date__year=current_year)
    [<Choice: Not much>, <Choice: The sky>, <Choice: Just hacking again>]
    
    # Let's delete one of the choices. Use delete() for that.
    >>> c = p.choice_set.filter(choice_text__startswith='Just hacking')
    >>> c.delete()
    

     最后你的polls_choice表里面应该如下

    总结:

    其实内容不多,主要就是演示了创建项目,创建应用,以及使用的几个主要的命令和文件

    主要命令 :

    djang-admin.py startproject prjname

    manage.py startapp appname

    主要文件:

    settings.py  用于配置,比如app,模版这些

    models.py 主要是和数据库配置相关

    数据库操作:

    创建数据:就相当于创建一个类对象,最后要使用save函数进行保存

    修改数据:使用primarykey获取对象后直接修改,save一下

    obj = Ojbcet.objects.get(pk=1)
    obj.sth = string
    obj.save()
    

     数据筛选:主要使用filter,可以使用

    关联数据库操作:需要在类名后面加上_set表明是一个数据集。

    下一篇主要学习django强大的后台管理。

    骑着毛驴看日出
  • 相关阅读:
    Spring IoC 容器概述
    OpenSSL生成SSL证书
    吴恩达老师深度学习课程Course4卷积神经网络-第二周课后作业
    吴恩达老师深度学习课程Course4卷积神经网络-第一周课后作业
    PageHelper在SpringBoot的@PostConstruct中不生效
    一个关于List的IndexOutOfBoundsException异常记录
    Mysql中通过关联update将一张表的一个字段更新到另外一张表中
    logback 常用配置(详解)
    Insert into select语句引发的生产事故
    Redis为什么变慢了?常见延迟问题定位与分析
  • 原文地址:https://www.cnblogs.com/linsir/p/4522272.html
Copyright © 2011-2022 走看看