django2.0入门教程第二节

成立模型

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的子类,类中的每个属性映射为一个字段,并标识了这么些字段的体系

扭转迁移

$ 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类的代码就转换成了数据表

继上篇
django2.0入门教程首节,生成了投票应用,接下去讲解如何拔取django的模型与数据库进行互相

django命令行交互

django提供了一个并行的shell,执行python manage.py shell即可进入相互界面,默认的互相界面不太好用,指出设置ipython,
pip install ipython,
这样,django会自动进入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__()函数将会再次回到我们定义好的数据格式。其它,我们还足以在models中添加自定义方法:

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

访问:http://127.0.0.1:8000/admin

输入账号密码进入后台

admin.png

sqlite,后台并从未观察我们树立的Question模型,需要将模型引入,才能在后台进行保障:

polls/admin.py

#_*_coding:utf8_*_
from django.contrib import admin
from .models import Question
admin.site.register(Question)

刷新后台页面,此时就能观察Question模型已经显现在页面了:

question.png

接下去就可以对数码举办添加,修改和删除操作

edit.png

数据库设置

开拓mysite/settings.py,可见到默认情形下,django使用的是sqlite3数据库

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

本学科便以默认的sqlite3作为数据库

注意settings.py的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激活的行使所需的数据表创制好了

源码下载

源码包地址

激活模型

mysite/settings.py

INSTALLED_APPS = [
    'polls.apps.PollsConfig',
    # ...
]
网站地图xml地图