继上篇 django2.0入门教程第一节,生成了投票应用,接下来讲解如何使用django的模型与数据库进行交互
数据库设置
打开mysite/settings.py,可看到默认情况下,django使用的是sqlite3数据库
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
本教程便以默认的sqlite3作为数据库
INSTALLED_APPS
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
这个选项代表django激活的应用,这些应用能被多个项目使用,你也可以将这些应用进行打包分发
有些应用要求我们必须至少要有一个数据库,如,django的后台,因此,让我们先来执行以下命令:
$ python manage.py migrate
Operations to perform:
Apply all migrations: admin, auth, contenttypes, sessions
Running migrations:
Applying contenttypes.0001_initial... OK
Applying auth.0001_initial... OK
Applying admin.0001_initial... OK
Applying admin.0002_logentry_remove_auto_add... OK
Applying contenttypes.0002_remove_content_type_name... OK
Applying auth.0002_alter_permission_name_max_length... OK
Applying auth.0003_alter_user_email_max_length... OK
Applying auth.0004_alter_user_username_opts... OK
Applying auth.0005_alter_user_last_login_null... OK
Applying auth.0006_require_contenttypes_0002... OK
Applying auth.0007_alter_validators_add_error_messages... OK
Applying auth.0008_alter_user_username_max_length... OK
Applying auth.0009_alter_user_last_name_max_length... OK
Applying sessions.0001_initial... OK
以上命令将django激活的应用所需的数据表创建好了
创建模型
django的模型(models)在本质上就是对数据表的定义。在django中是不需要直接与数据库交互的,所有对数据库的操作都可以映射为模型类的操作,有一个数据表,就有一个模型类与之对应
polls/models.py
#_*_coding:utf8_*_
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, on_delete=models.CASCADE)
choice_text = models.CharField(max_length=200)
votes = models.IntegerField(default=0)
以上代码相当简单明了,每个类都是models.Model的子类,类中的每个属性映射为一个字段,并标识了这些字段的类型
激活模型
mysite/settings.py
INSTALLED_APPS = [
'polls.apps.PollsConfig',
# ...
]
生成迁移
$ python manage.py makemigrations polls
Migrations for 'polls':
polls/migrations/0001_initial.py
- Create model Choice
- Create model Question
- Add field question to choice
自动生成了polls/migrations/0001_initial.py文件,现在还没有真正创建数据表,需要再执行数据迁移才能生成数据表,在此之前,先来预览要执行的sql语句:
$ python manage.py sqlmigrate polls 0001
BEGIN;
--
-- Create model Choice
--
CREATE TABLE "polls_choice" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "choice_text" varchar(200) NOT NULL, "votes" integer NOT NULL);
--
-- Create model Question
--
CREATE TABLE "polls_question" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "question_text" varchar(200) NOT NULL, "pub_date" datetime NOT NULL);
--
-- Add field question to choice
--
ALTER TABLE "polls_choice" RENAME TO "polls_choice__old";
CREATE TABLE "polls_choice" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "choice_text" varchar(200) NOT NULL, "votes" integer NOT NULL, "question_id" integer NOT NULL REFERENCES "polls_question" ("id") DEFERRABLE INITIALLY DEFERRED);
INSERT INTO "polls_choice" ("id", "choice_text", "votes", "question_id") SELECT "id", "choice_text", "votes", NULL FROM "polls_choice__old";
DROP TABLE "polls_choice__old";
CREATE INDEX "polls_choice_question_id_c5b4b260" ON "polls_choice" ("question_id");
COMMIT;
以上的sql语句就是从polls/migrations/0001_initial.py文件中生成
执行迁移,即执行以上的sql语句:
$ python manage.py migrate
Operations to perform:
Apply all migrations: admin, auth, contenttypes, polls, sessions
Running migrations:
Applying polls.0001_initial... OK
至此,models类的代码就转换成了数据表
django命令行交互
python manage.py shellpip install ipython
用交互客户端测试对数据库的操作:
$ python manage.py shell
Python 3.6.2 (default, Nov 22 2017, 14:09:09)
Type 'copyright', 'credits' or 'license' for more information
IPython 6.2.1 -- An enhanced Interactive Python. Type '?' for help.
In [1]: from polls.models import Question, Choice
In [2]: from django.utils import timezone
In [3]: q = Question(question_text='问题1', pub_date=timezone.now())
In [4]: q.save() # 添加一条记录
In [5]: q.id
Out[5]: 1
In [6]: q.question_text
Out[6]: '问题1'
In [7]: q.pub_date
Out[7]: datetime.datetime(2017, 12, 29, 8, 39, 20, 968497, tzinfo=<UTC>)
In [8]: q.question_text = '问题2'
In [9]: q.save()
In [10]: Question.objects.all()
Out[10]: <QuerySet [<Question: Question object (1)>]>
以上对数据库的查询,得到的只是一个对象,看起来并不直观,我们修改下polls/models.py,让结果显示更友好
polls/models.py
from django.db import models
class Question(models.Model):
# ...
def __str__(self):
return self.question_text
class Choice(models.Model):
# ...
def __str__(self):
return self.choice_text
__str__()
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)
注意,修改models文件后,需要退出再重新进入交互界面,退出按ctrl+d
$ python manage.py shell
Python 3.6.2 (default, Nov 22 2017, 14:09:09)
Type 'copyright', 'credits' or 'license' for more information
IPython 6.2.1 -- An enhanced Interactive Python. Type '?' for help.
In [1]: from polls.models import Question, Choice
In [2]: Question.objects.all() # 获取所有问题
Out[2]: <QuerySet [<Question: 问题2>]>
In [3]: Question.objects.filter(id=1) # 获取id为1的数据
Out[3]: <QuerySet [<Question: 问题2>]>
In [8]: Question.objects.filter(question_text__startswith='问题') # 获取内容包含'问题'的数据
Out[8]: <QuerySet [<Question: 问题2>]>
In [9]: from django.utils import timezone
In [10]: current_year = timezone.now().year
In [11]: Question.objects.get(pub_date__year=current_year)
Out[11]: <Question: 问题2>
In [12]: Question.objects.get(id=2) # 当获取的数据不存在时,会报以下错误
---------------------------------------------------------------------------
DoesNotExist Traceback (most recent call last)
<ipython-input-12-75091ca84516> in <module>()
----> 1 Question.objects.get(id=2)
In [13]: Question.objects.get(pk=1)
Out[13]: <Question: 问题2>
In [14]: q = Question.objects.get(pk=1)
In [15]: q.was_published_recently() # 调用自定义的方法
Out[15]: True
In [16]: q = Question.objects.get(pk=1)
In [17]: q.choice_set.all()
Out[17]: <QuerySet []>
In [19]: q.choice_set.create(choice_text='选项1', votes=0)
Out[19]: <Choice: 选项1>
In [20]: q.choice_set.create(choice_text='选项2', votes=0)
Out[20]: <Choice: 选项2>
In [21]: c = q.choice_set.create(choice_text='选项3', votes=0)
In [22]: c.question
Out[22]: <Question: 问题2>
In [23]: q.choice_set.all()
Out[23]: <QuerySet [<Choice: 选项1>, <Choice: 选项2>, <Choice: 选项3>]>
In [24]: q.choice_set.count()
Out[24]: 3
In [25]: Choice.objects.filter(question__pub_date__year=current_year)
Out[25]: <QuerySet [<Choice: 选项1>, <Choice: 选项2>, <Choice: 选项3>]>
In [26]: c = q.choice_set.filter(choice_text__startswith='选项3')
In [27]: c.delete()
Out[27]: <bound method QuerySet.delete of <QuerySet [<Choice: 选项3>]>>
In [29]: Choice.objects.filter(question__pub_date__year=current_year)
Out[29]: <QuerySet [<Choice: 选项1>, <Choice: 选项2>]>
创建后台管理员
django自带了一个管理后台,我们只需创建一个管理员用户即可使用
创建一个后台管理员用户:
$ python manage.py createsuperuser
Username (leave blank to use 'root'): admin
Email address: admin@example.com
Password:
Password (again):
Superuser created successfully.
密码自己设置,如设置为: 123admin456
输入账号密码进入后台
后台并没有看到我们建立的Question模型,需要将模型引入,才能在后台进行维护:
polls/admin.py
#_*_coding:utf8_*_
from django.contrib import admin
from .models import Question
admin.site.register(Question)
刷新后台页面,此时就能看到Question模型已经展现在页面了:
接下来就可以对数据进行添加,修改和删除操作