美文网首页我爱编程
Django -- Polls - Part 2

Django -- Polls - Part 2

作者: liaozb1996 | 来源:发表于2018-03-19 18:31 被阅读0次
  • 数据库配置
  • 创建 Model
  • Django Admin

本节包含的内容较多:Polls - Part 2


数据库配置

Django 默认配置就可以直接使用 SQLite
在生产环境中,可以会使用适合大规模的数据库,如 Mysql

配置

# mysite/settings.py

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}
  • ENGINE

    • django.db.backends.sqlite3
    • django.db.backends.postgresql
    • django.db.backends.mysql
    • django.db.backends.oracle
    • 其他
  • NAME:数据库的名称

  • USERNAME

  • PASSWORD

  • HOST

  • 其他参数

  • 创建数据库: CREATE DATABASE <database_name>;

指定的数据库用户要有创建数据库的权限:用于创建 test database

国际化设置

# Internationalization
# https://docs.djangoproject.com/en/2.0/topics/i18n/

LANGUAGE_CODE = 'zh-hans'

TIME_ZONE = 'Asia/Shanghai'

USE_I18N = True

USE_L10N = True

USE_TZ = True # True 用 TIME_ZONE 显示模板和表单中的日期时间
            #  False 用 TIME_ZONE 保存日期时间 (datetimes)

INSTALLED_APPS

INSTALLED_APPS 中包含着已激活的APP,如果这个列表中的APP需要用到数据库,Django会根据Model的定义来生成对应的 migration (创建数据库所需的SQL语句)

如果不需要某项功能,可以将对应的 APP 注释掉

$ python manage.py makemigrations # 如果要添加自定义的APP,需要运行该命令生成 migration 文件
$ python manage.py migrate # 根据 migration 文件,创建对应的数据库表

migrate 命令


在数据库客户端中查看 Django 创建的数据库表的命令:

  • PostgreSQL:\dt
  • MySQL:SHOW TABLES
  • SQLite:.schema
  • Oracle: SELECT TABLE_NAME FROM USER_TABLES;

创建 Model

Model 用 Python Class 表示;Django 根据 Model 的定义生成 migration (创建数据库所需的SQL) 和 操作数据库的 API

Model Class --> 数据库表
Field --> 数据库的列
Field Name --> 数据库的列名

创建两个数据库表 QuestionChoice

Django 会自动创建一个名为 id 主键 (primary key),并自动增加它的值

# polls/models.py

from django.db import models

# Create your models here.

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

    def __str__(self):  # 返回代表对象的字符串
        return self.question_text

class Choice(models.Model):
    question = models.ForeignKey(Question, on_delete=models.CASCADE)
    choice_text = models.CharField(max_length=200)
    vote = models.IntegerField(default=0)

    def __str__(self):
        return self.choice_text

fields

Field

  • 有的 Field 的参数是必须要有的:比如 CharField 必须有 max_length
  • 有的 Field 的参数是可选的:比如 IntegerFielddefault

将 APP 的 config class 添加到 INSTALLED_APPS 中


config class 在 polls/apps.py
# mysite/settings.py

INSTALLED_APPS = [
    'polls.apps.PollsConfig', # 向 Django 添加 Polls
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
]

$ python manage.py makemigrations # 生成 migration 文件,每次修改 Model 之后执行
$ python manage.py sqlmigrate polls 0001 # 查看具体的SQL语句
$ python manage.py check # 检查项目是否有错误
$ python manage.py migrate # 根据 migration 创建数据库表

migrate 可以在保留数据库中数据的情况下,修改 Model

Datebase API

$ python manage.py shell

>>> from polls.models import Question, Choice

>>> Question.objects.all()
<QuerySet []>
>>>
>>> from django.utils import timezone # 带有时区信息的 datetime, Django 默认配置是启用时区的

>>> Question.objects.create(question_text="What's up", pub_date=timezone.now())
<Question: What's up>   # __str__()
>>> Question.objects.all()
<QuerySet [<Question: What's up>]>

>>> q = Question.objects.all()[0]
>>> q
<Question: What's up>
>>> q.id
1

>>> q.save()  # 将创建的对象保存到数据库中
>>> q.question_text
"What's up"
>>> q.pub_date
datetime.datetime(2018, 3, 19, 15, 0, 48, 914868, tzinfo=<UTC>)

time zone support docs

添加自定义的API

# polls/models.py
from django.utils import timezone
import datetime

class Question(models.Model):
    ...
    
    def was_published_recently(self): # 判断 “问题” 是否是在一天内发布
         return timezone.now() - self.pub_date < datetime.timedelta(days=1)

$ python manage.py shell

>>> from polls.models import Question, Choice
>>> q = Question.objects.get(pk=1)
>>> q
<Question: What's up>
>>> q.was_published_recently()
True

Lookup API

# get 返回匹配的第一项,filter 返回所有匹配的集合
>>> q = Question.objects.get(pk=1)
>>> q
<Question: What's up>

>>> Question.objects.filter(id=1)
<QuerySet [<Question: What's up>]>
>>>
>>> Question.objects.filter(pk=1)  # 主键 primary key
<QuerySet [<Question: What's up>]>
>>>
>>> Question.objects.filter(question_text__startswith='What')
<QuerySet [<Question: What's up>]>
>>>
>>>
>>> from django.utils import timezone
>>> current_year = timezone.now().year
>>>
>>> Question.objects.filter(pub_date__year=current_year)  # 今年发布的问题
<QuerySet [<Question: What's up>]>
>>>

# 外键可以相互访问
>>> q.choice_set.all() #问题的所有选项
<QuerySet []>

# 创建问题的选项
>>> q.choice_set.create(choice_text="Nice")
<Choice: Nice>
>>> c = q.choice_set.create(choice_text="so so", vote=0)
>>>
>>> q.choice_set.all()
<QuerySet [<Choice: Nice>, <Choice: so so>]>

>>> Choice.objects.filter(question__pub_date__year=current_year) # 今年发布的问题的选项
<QuerySet [<Choice: Nice>, <Choice: so so>]>

>>> q
<Question: What's up>
>>> c = q.choice_set.filter(choice_text__startswith='so')
>>> c
<QuerySet [<Choice: so so>]>
>>> c.delete() # 删除选项
(1, {'polls.Choice': 1})

For more information on model relations, see Accessing related objects. For more on how to use double underscores to perform field lookups via the API, see Field lookups. For full details on the database API, see our Database API reference.

Django Admin 后台管理

$ python manage.py createsuperuser
$ python manage.py runserver

127.0.0.1:8000/admin/
Django Admin

为 Polls 创建管理接口

# polls/admin.py
from django.contrib import admin
from .models import Question

admin.site.register(Question)
Admin Interface

相关文章

  • Django -- Polls - Part 2

    数据库配置 创建 Model Django Admin 本节包含的内容较多:Polls - Part 2 数据库配...

  • Django -- Polls - Part 3

    URL dispatcher View 视图 通过Python函数(或一个类的方法)来生成一个页面;可能会涉及通过...

  • Django -- Polls - Part 4

    Form 如果是从服务器获取信息,使用 GET;如果是要从服务器修改信息,使用 POST;发生敏感信息,使用 PO...

  • Django -- Polls - Part 1

    创建项目结构 创建 APP -- Polls 结构 创建视图 View 配置/声明 URL -- URLconf ...

  • Django -- Polls - Part 7

    定制 Django Admin 步骤: 创建 admin.ModelAdmin 将子类作为 admin.site....

  • Django -- Polls - Part 6

    Django 渲染一个页面所需的图片,CSS, Javascript 称为静态文件 CSS 在APP下创建目录:p...

  • Django study

    [TOC] Django study creating a project 调试 demo-the Polls a...

  • 2019-03-08 django操作模型

    如果在django中修改了应用model,需要执行2条命令我们以django官方文档中的polls应用为例 然后应...

  • django入门基础指令

    安装django指令 新建项目(名称为mysite) 运行django项目 创建应用(名称为polls) 为应用生...

  • Django简易教程之二(admin)

    说明:本文翻译自Django官方文档Writing your first Django app, part 2。 ...

网友评论

    本文标题:Django -- Polls - Part 2

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