啊峰哥

2 第一个Django应用 第1部分(数据库与模型)

目标应用:

  • 一个公开的网站,可以让访客查看投票的结果并让他们进行投票。
  • 一个后台管理网站,你可以添加、修改和删除选票。

    查看django版本

  python -c "import django; print(django.get_version())"

2.1创建一个项目

   django-admin startproject mysite

mange.py:命令行工具
mysite/:项目的真正python包,导入时需要使用python包名字,如mysite.urls
mysite/setting.py:Django项目的配置
mysite/urls.py:Django站点的目录
mysite/wsgi.py:用于项目的WSGI兼容的Web服务器入口

2.2数据库的建立

    默认数据库使用SQLite,在setting.py文件的DATABASES‘default’中,可以修改数据库设置。ENGINE为支持的数据库,NAME为数据库名称,默认为os.path.join(BASE_DIR, 'db.sqlite3')
 
python manage.py migrate 根据数据库设置自动创建数据库表
python manage.py runserver 启动Django开发服务器,默认端口8000
python manage.py runserver 8080 使用8080端口
python manage.py runserver 0.0.0.0:8000 其他电脑上展示

2.3创建模型

    项目:项目是一个特定网站中相关配置和应用的集合。
    应用:应用是一个Web应用程序,它完成具体的事项——比如一个博客系统、一个存储公共档案的数据库或者一个简单的投票应用。可以运用于多个项目。
    开发环境建立后,使用python manage.py startapp polls创建应用。

 

结构如下
polls/
    __init__.py
    admin.py
    migrations/
        __init__.py
    models.py
    tests.py
    views.py

    当编写一个数据库驱动的Web应用时,第一步就是定义该应用的模型 —— 本质上,就是定义该模型所对应的数据库设计及其附带的元数据。
    这个简单的投票应用中,我们将创建两个模型: QuestionChoice
polls/models.py
from django.db import models 
#通过Field类的实例表示字段,告诉Django,每个字段中保存着什么类型的数据。
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)  #ForeignKey定义了一个关联。它告诉Django每个Choice都只关联一个Question
    choice_text = models.CharField(max_length=200)
    votes = models.IntegerField(default=0)

2.4激活模型

    第一步.告诉项目polls应用安装

再次编辑mysite/settings.py文件,并修改INSTALLED_APPS设置以包含字符串'polls'。所以它现在是这样的:

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为这些修改创建迁移文件
    python manage.py migrate将这些改变更新到数据库中。

2.5玩转API

先修改models.py,添加__str__()方法给Question和Choice,不仅会使你自己在使用交互式命令行时看得更加方便,而且会在Django自动生成的管理界面中使用对象的这种表示。
polls/models.py
from django.db import models

class Question(models.Model):
    # ...
    def __str__(self):                     r
        return self.question_text

class Choice(models.Model):
    # ...
    def __str__(self):                      
        return self.choice_text
python manage.py shell 
进入python环境,;路径为mysite/setting.py文件的路径
>>> from polls.models import Question, Choice   
# 导入刚写的模型
# 查看所有对象
>>> Question.objects.all()
[]
#使用timezone代替datetime.now()防止出错

>>> from django.utils import timezone
>>> q = Question(question_text="What's new?", pub_date=timezone.now())

#保存对象
>>> q.save()
>>> q.id
1
#查看属性
>>> q.question_text
"What's new?"
>>> q.pub_date
datetime.datetime(2012, 2, 26, 13, 0, 0, 775217, tzinfo=<UTC>)

# 改变属性
>>> q.question_text = "What's up?"
>>> q.save()

# 查看所有对象
>>> Question.objects.all()
[<Question: Question object>]


添加一个自定义方法
polls/models.py
import datetime

from django.db import models
from django.utils import timezone


class Question(models.Model):
    # ...
    def was_published_recently(self):
        return self.pub_date >= timezone.now() - datetime.timedelta(days=1)
保存这些改动,然后通过python manage.py shell再次打开一个新的Python 交互式shell:
>>> from polls.models import Question, Choice

>>> Question.objects.all()
[<Question: What's up?>]

# Django提供了一个丰富的数据库查找API,通过关键字查找。
>>> Question.objects.filter(id=1)
[<Question: What's up?>]
>>> Question.objects.filter(question_text__startswith='What')
[<Question: What's up?>]

# 获取与今年年份相等的对象
>>> from django.utils import timezone
>>> current_year = timezone.now().year
>>> Question.objects.get(pub_date__year=current_year)
<Question: What's up?>

# 如果ID不存在,报错
>>> Question.objects.get(id=2)
Traceback (most recent call last):
    ...
DoesNotExist: Question matching query does not exist.

# 由主键查找是最常见的情况,因此Django提供了一种对主键精确查找的快捷方式。下面的内容与问题.objects.get(id=1)相同。
>>> Question.objects.get(pk=1)
<Question: What's up?>

# 查看定义的方法是否可用
>>> q = Question.objects.get(pk=1)
>>> q.was_published_recently()
True

# 显示所有相关对象集
>>> q.choice_set.all()
[]

# 用create创建新对象.
>>> 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)

# 通过API访问关联的对象
>>> c.question
<Question: What's up?>

# 反之也成立
>>> q.choice_set.all()
[<Choice: Not much>, <Choice: The sky>, <Choice: Just hacking again>]
>>> q.choice_set.count()
3

# 选择查看对象
>>> Choice.objects.filter(question__pub_date__year=current_year)
[<Choice: Not much>, <Choice: The sky>, <Choice: Just hacking again>]

# 删除对象
>>> c = q.choice_set.filter(choice_text__startswith='Just hacking')
>>> c.delete()

posted on 2017-10-21 22:59  啊峰哥  阅读(176)  评论(0编辑  收藏  举报

导航