美文网首页测试开发
Django_初识(一)

Django_初识(一)

作者: 古佛青灯度流年 | 来源:发表于2016-10-21 09:08 被阅读38次

学习笔记

一、创建一个服务器

需求:

1.熟悉操作命令
2.连接mysql数据库.
3.创建app=》polls
4.熟悉django的数据库操作命令

实践:

  • 安装Django:
    1.我用的是Mac版pycharm,所以直接用内置安装第三方工具安装的Django

  • 校验django是否安装成功

    $ python -c "import django; print(django.get_version())"
    
  • 新建项目名:

    django-admin startproject mysite
    

    注:报错找不到django-admin解决方案:向/usr/local/bin/中添加软连接,也有可能是当前python路径没有执行权限sudo chmod +x django-admin.py

    软连接:

    sudo ln -s /usr/local/python27/python_path/django-admin.py /usr/local/bin/django-admin.py
    
  • 设置TIME_ZONE:
    TIME_ZONE ='Asia/Shanghai'

  • 使用Mysql数据库

    • mysite/settings.py中设置:
    
    DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.mysql',
            'NAME': 'db_wph',
            'USER': 'root',
            'PASSWORD': '123456',
            'HOST': '127.0.0.1',
            'PORT': '3306'
        }
    }
    
    • 然后使用命令:

      $ python manage.py migrate
      
  • 测试一下服务器是否搭建成功:

    $ python manage.py runserver
    
    Performing system checks...
    
    0 errors found
    May 13, 2015 - 15:50:53
    Django version 1.8, using settings 'mysite.settings'
    Starting development server at http://127.0.0.1:8000/
    Quit the server with CONTROL-C.
    

    浏览器中输入网址:http://127.0.0.1:8000/

  • control+c结束进程服务,并释放8000端口

    指定端口命令$ python manage.py runserver 8080

    监听所有端口:

    $ python manage.py runserver 0.0.0.0:8000
    
  • 新建一个app=》polls

    $ python manage.py startapp polls
    
    polls/
        __init__.py
        admin.py
        migrations/
            __init__.py
        models.py
        tests.py
        views.py
    
    • 修改polls/models.py
    
    from django.db import models
    

class Question(models.Model):
question_text = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')

class Choice(models.Model):
question = models.ForeignKey(Question)
choice_text = models.CharField(max_length=200)
votes = models.IntegerField(default=0)


- 激活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',
)
​```
  • 运行命令:

    $ python manage.py makemigrations polls 
    

    通过运行makemigrations告诉Django,已经对模型做了一些更改(在这个例子中,你创建了一个新的模型)并且会将这些更改存储为迁移文件

  • 运行迁移命令:

    $ python manage.py sqlmigrate polls 0001
    
    • 再次运行migrate以在你的数据库中创建模型所对应的表:将这些改变更新到数据库中。

      $ python manage.py migrate
      
  • 进入mysql查看表结构

    mysql> show tables;
    +----------------------------+
    | Tables_in_db_wph           |
    +----------------------------+
    | auth_group                 |
    | auth_group_permissions     |
    | auth_permission            |
    | auth_user                  |
    | auth_user_groups           |
    | auth_user_user_permissions |
    | city_list                  |
    | django_admin_log           |
    | django_content_type        |
    | django_migrations          |
    | django_session             |
    | polls_choice               |
    | polls_question             |
    | supplier                   |
    +----------------------------+
    14 rows in set (0.00 sec)
    

  • 了解api命令 -操作数据库命令

    • 进入shell
    $ python manage.py shell
    
    >>> from polls.models import Question, Choice   # Import the model classes we just wrote.
    
    # No questions are in the system yet.
    >>> Question.objects.all()
    []
    
    # Create a new Question.
    # 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
    >>> q = Question(question_text="What's new?", pub_date=timezone.now())
    
    # Save the object into the database. You have to call save() explicitly.
    >>> q.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.
    >>> q.id
    1
    
    # Access model field values via Python attributes.
    >>> q.question_text
    "What's new?"
    >>> q.pub_date
    datetime.datetime(2012, 2, 26, 13, 0, 0, 775217, tzinfo=<UTC>)
    
    # Change values by changing the attributes, then calling save().
    >>> q.question_text = "What's up?"
    >>> q.save()
    
    # objects.all() displays all the questions in the database.
    >>> Question.objects.all()
    [<Question: Question object>]
    

    mysql> select * from  polls_question;
    +----+---------------+----------------------------+
    | id | question_text | pub_date                   |
    +----+---------------+----------------------------+
    |  1 | what's up?    | 2016-10-20 06:58:26.437937 |
    +----+---------------+----------------------------+
    
    mysql> select * from  polls_choice;
    +----+--------------------+-------+-------------+
    | id | choice_text        | votes | question_id |
    +----+--------------------+-------+-------------+
    |  1 | Not much           |     0 |           1 |
    |  2 | The sky            |     0 |           1 |
    +----+--------------------+-------+-------------+
    3 rows in set (0.00 sec)
    
    >>> from polls.models import Question, Choice
    
    # Make sure our __str__() addition worked.
    >>> Question.objects.all()
    [<Question: What's up?>]
    
    # Django provides a rich database lookup API that's entirely driven by
    # keyword arguments.
    >>> Question.objects.filter(id=1)
    [<Question: What's up?>]
    >>> Question.objects.filter(question_text__startswith='What')
    [<Question: What's up?>]
    
    # Get the question that was published this year.
    >>> from django.utils import timezone
    >>> current_year = timezone.now().year
    >>> Question.objects.get(pub_date__year=current_year)
    <Question: What's up?>
    
    # Request an ID that doesn't exist, this will raise an exception.
    >>> Question.objects.get(id=2)
    Traceback (most recent call last):
        ...
    DoesNotExist: Question 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 Question.objects.get(id=1).
    >>> Question.objects.get(pk=1)
    <Question: What's up?>
    
    # Make sure our custom method worked.
    >>> q = Question.objects.get(pk=1)
    >>> q.was_published_recently()
    True
    
    # Give the Question 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 question's choice) which can be accessed via the API.
    >>> q = Question.objects.get(pk=1)
    
    # Display any choices from the related object set -- none so far.
    >>> q.choice_set.all()
    []
    
    # Create three choices.
    >>> q.choice_set.create(choice_text='Not much', votes=0)
    <Choice: Not much>
    >>> q.choice_set.create(choice_text='The sky', votes=0)
    <Choice: The sky>
    >>> c = q.choice_set.create(choice_text='Just hacking again', votes=0)
    
    # Choice objects have API access to their related Question objects.
    >>> c.question
    <Question: What's up?>
    
    # And vice versa: Question objects get access to Choice objects.
    >>> q.choice_set.all()
    [<Choice: Not much>, <Choice: The sky>, <Choice: Just hacking again>]
    >>> q.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 question whose pub_date is in this year
    # (reusing the 'current_year' variable we created above).
    >>> Choice.objects.filter(question__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 = q.choice_set.filter(choice_text__startswith='Just hacking')
    >>> c.delete()
    

相关文章

  • Django_初识(一)

    学习笔记 一、创建一个服务器 需求: 1.熟悉操作命令2.连接mysql数据库.3.创建app=》polls4.熟...

  • Django安装教程

    windows下安装Django_百度经验

  • Django_中文教程[www.rejoiceblog.com]

    下载地址:Django_中文教程[www.rejoiceblog.com].pdf

  • django_缓存

    一、什么是缓存 我的理解就是将数据信息,保存在数据库以外的地方,当然也可以保存到数据库,做到一种数据延迟的效果,降...

  • django_分页

    一、基础篇 =view模块处理 html 页面 二、讲解 对页数限制的讲解 转换成代码 上一页/下一页操作 代码如...

  • django_多表查询

    一、一对多 利用ForeignKey 创建表 注关联表中会自动添加字段后面加_id,相当于publish _id,...

  • Django_完善博客

    通过写一个博客项目,来串联自己的知识点,并总结一些小的技巧 页面介绍 1.博客主页面 2.博客文章内容页面...

  • Django_学习前言

    开始学习Django,这个系列都是自己学习然后码字,比较辛苦,但是我真的好喜欢整理笔记啊!丧心病狂~~~~~...

  • Django_基本使用

    创建项目 django-admin startproject 项目名称__init__.py:说明mysql_dj...

  • Django_补充小技巧

    1.Templates过滤器 什么是过滤器? 写在模板中,属于Django模板语言 可以修改模板中的变量,...

网友评论

    本文标题:Django_初识(一)

    本文链接:https://www.haomeiwen.com/subject/uuiquttx.html