- 数据库配置
- 创建 Model
- Django Admin
本节包含的内容较多:Polls - Part 2
数据库配置
Django 默认配置就可以直接使用 SQLite
在生产环境中,可以会使用适合大规模的数据库,如 Mysql
配置
- 安装驱动 (Database bingings)
- 修改项目配置文件
# mysite/settings.py
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
-
django.db.backends.sqlite3
django.db.backends.postgresql
django.db.backends.mysql
django.db.backends.oracle
- 其他
NAME:数据库的名称
创建数据库:
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语句)
-
django.contrib.admin
– The admin site. You’ll use it shortly. -
django.contrib.auth
– An authentication system. -
django.contrib.contenttypes
– A framework for content types. -
django.contrib.sessions
– A session framework. -
django.contrib.messages
– A messaging framework. -
django.contrib.staticfiles
– A framework for managing static files.
如果不需要某项功能,可以将对应的 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 --> 数据库的列名
创建两个数据库表 Question
和 Choice
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
Field
- 有的 Field 的参数是必须要有的:比如
CharField
必须有max_length
- 有的 Field 的参数是可选的:比如
IntegerField
的default
将 APP 的 config class 添加到 INSTALLED_APPS 中
# 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>)
添加自定义的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/
为 Polls 创建管理接口
# polls/admin.py
from django.contrib import admin
from .models import Question
admin.site.register(Question)