三、数据库
1、建立数据库
Django为多种数据库后台提供了统一的调用API。根据需求不同,Django可以选择不同的数据库后台,有:PostgreSQL、SQLite3、MySQL、Oracle。默认情况下,配置使用SQLite3,SQLite3包含在Python中,所以不需要安装任何东西来支持你的数据库。但是,当开始你的第一个真正项目时,你可能想要使用一个更可扩展的数据库,我们这里以Django连接MySQL数据库为例。
在cmd中输入:
mysql -uroot -p
输入密码后,在MySQL中建立项目的数据库polls:
mysql> CREATE DATABASE polls DEFAULT CHARSET=utf8;
这里使用utf8作为默认字符集,以便支持中文。
在MySQL中为Django项目创立用户,并授予相关权限:
mysql> GRANT SELECT, INSERT, UPDATE, DELETE, CREATE, DROP, INDEX, ALTER, CREATE TEMPORARY TABLES, LOCK TABLES, REFERENCES ON polls.* TO 'admin'@'localhost' IDENTIFIED BY 'admin123456.';
//grant all privileges on 想授权的数据库.* to 'user1'@'%';
//flush privileges;
在settings.py中,将DATABASES对象更改为:
DATABASES = {
'default': {
# 'ENGINE': 'django.db.backends.sqlite3',
# 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
'ENGINE': 'django.db.backends.mysql',
'NAME': 'polls',
'USER': 'admin',
'PASSWORD': 'admin123456.',
'HOST': 'localhost',
'PORT': '3306', # 默认
}
}
设置完之后要检查是否已安装MySQLdb模块,否则服务器无法启动。在Python shell中输入:
import MySQLdb
若上报ImportError: No module named MySQLdb,则未安装MySQLdb模块。
对于不同的系统和程序有如下的解决方法:
easy_install mysql-python (mix os)
pip install mysql-python (mix os)
apt-get install python-mysqldb (Linux Ubuntu)
cd/usr/ports/databases/py-MySQLdb && make install clean (FreeBSD)
yum install MySQL-python (linux Fedora, CentOS)
pip install mysqlclient (Windows)亲测可用
**PS:**Mysql相关资料:
- MySQL下载安装、配置与使用(win7x64)
- Navicat for MySQL下载、安装与破解
- Navicat for MySQL 11.2.15 中文免费版
- mysql数据库管理工具navicat for mysql怎么用
- Windows下Mysql5.7忘记root密码的解决方法
2、创建模型
模型,实质上就是您的数据库布局,并附加元数据。在Django中,每个模型都由一个继承自django.db.models.Model的子类来表示,每个模型都有许多类变量,每个变量表示模型中的数据库字段。
MySQL是关系型数据库,但在Django的帮助下,我们不用直接编写SQL语句。Django将关系型的表(table)转换成为一个类(class),每个记录(record)是该类下的一个对象(object),表的每一列(column)是该类的一个属性(field)。这样,我们就可以使用基于对象的方法,来操纵关系型的MySQL数据库。
在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('发布日期')
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)
votes = models.IntegerField(default = 0)
def __str__(self):
return self.choice_text
接着需要同步数据库,在cmd中分别输入:
# 1. 创建更改的文件
python manage.py makemigrations#后面可加上要同步的对应app名称
# 2. 将生成的py文件应用到数据库
python manage.py migrate##后面可加上要同步的对应app名称
成功后,会创建polls/migrations/0001_initial.py文件。打开文件可发现,Django会自动增加一个id列,作为记录的主键(Primary Key)。
想看到同步数据库过程中运行的SQL语句,可在cmd中输入:
python manage.py sqlmigrate polls 0001
检查同步过程中的问题,可在cmd中输入:
python manage.py check
3、使用数据库API
Django提供了丰富的数据库API,我们可以进入该项目的Python shell中使用它,使用以下命令调用Python shell:
python manage.py shell
在Python shell中使用数据库API,代码如下:
>>> from polls.models import Question, Choice # Import the model classes we just wrote.
# No questions are in the system yet.
>>> Question.objects.all()
<QuerySet []>
# 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.
>>> 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()
<QuerySet [<Question: Question object (1)>]>
使用自定义方法,进一步探索数据库API,先在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的标准datetime模块和Django的timezone模块,可参考文档time zone support docs。
在Python shell中使用数据库API,代码如下:
>>> from polls.models import Question, Choice
# Make sure our __str__() addition worked.
>>> Question.objects.all()
<QuerySet [<Question: What's up?>]>
# Django provides a rich database lookup API that's entirely driven by
# keyword arguments.
>>> Question.objects.filter(id=1)
<QuerySet [<Question: What's up?>]>
>>> Question.objects.filter(question_text__startswith='What')
<QuerySet [<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()
<QuerySet []>
# 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()
<QuerySet [<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)
<QuerySet [<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()
想了解更多有关模型关系的信息,可参考Accessing related objects。了解更多有关如何使用双下划线查找字段的信息,可参考Field lookups。数据库API的完整详细信息,请查阅Database API reference。
4、在网页显示数据
在polls/views.py中,定义视图函数survey,并从数据库中读取记录,代码如下:
from django.shortcuts import render
from django.http import HttpResponse
from polls.models import Question, Choice
# Create your views here.
def index(request):
return HttpResponse('Hello, world! You\'re at the polls index. ')
def survey(request):
q1 = Question.objects.get(id=1)
q1_str = str(q1)
choice_list = q1.choice_set.all()
choice_str = map(str, choice_list)
return HttpResponse("<p>" + q1_str +':'+ ' '.join(choice_str) + "</p>")
在polls/urls.py中,进行URL配置(前面已在mysite/urls.py中设置polls.urls访问对象),代码如下:
from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name = 'index'),
path('survey/', views.survey, name = 'survey'),
]
运行服务器,在浏览器中输入URL:127.0.0.1:8001/polls/survey查看效果。
5、后台管理admin
admin界面通常在mysite/urls.py中已经设置好,位于path(‘admin/’, admin.site.urls),使用如下。
首先,需要创建一个可以登录管理网站的账号,在cmd中输入:
python manage.py createsuperuser
填写用户名、邮箱和密码,这里我们创建了一个admin账号。
接着需要将数据模型注册到admin中,修改polls/admin.py文件(如果没有新建一个),代码如下:
from django.contrib import admin
from .models import Question, Choice
# Register your models here.
admin.site.register(Question)
admin.site.register(Choice)
运行服务器,在浏览器中输入URL:127.0.0.1:8001/admin,填写前面创建的用户名和密码,就可以查看效果。
参考资料