本文将配置数据库,创建模型,简单介绍Django自动生成的管理网站。


数据库配置

打开mysite/settings.py文件,这是Django的配置文件。

默认使用SQLite数据库,Python包含SQLite,所以不需要安装其他程序来支持数据库。

如果想使用其它数据库,还需要安装相应的数据库驱动,并修改DATABASES 'default' 项中的以下设置:

  • ENGINE —— 'django.db.backends.sqlite3'、'django.db.backends.postgresql'、'django.db.backends.mysql'或'django.db.backends.oracle'。或者其它数据库。
  • NAME —— 数据库名。

如果不使用SQLite,还需要设置USERPASSWORDHOST,详见配置数据库。

设置语言为简体中文:

LANGUAGE_CODE = 'zh-Hans'

设置时区为东八区:

TIME_ZONE = 'Asia/Shanghai'

INSTALLED_APPS中的默认应用需要至少一个数据库表,所以现在需要创建数据库表,在PyCharm的Terminal中执行以下命令:

py manage.py migrate

创建模型

我们将创建两个模型:QuestionChoice。一个Question包含一个问题和发布时间,一个Choice包含选择文本和投票计数。每个Choice都和一个Question关联。

编辑polls/models.py,如下所示:

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)

model代表数据库表,model中的变量代表数据库表中的字段(变量名即字段名)。


激活模型

Django根据模型自动创建数据库表和访问数据库表中对象的Python API

但需要首先将polls应用配置到project中,即将polls/apps.py中的PollsConfig类配置到mysite/settings.py中,如下所示:

INSTALLED_APPS = [
    'polls.apps.PollsConfig',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
]

执行以下命令:

py manage.py makemigrations polls

改变模型后执行makemigrations命令可以令Django生成数据库迁移文件,用于记录数据库变更历史,这里生成了polls/migrations/0001_initial.py。

执行migrate命令来创建数据库表:

py manage.py migrate

记住,改变模型时需要做以下三步:

  1. 改变models.py中的模型;
  2. 执行py manage.py makemigrations来创建数据库迁移文件;
  3. 执行py manage.py migrate来修改数据库。

试用Django API

执行以下命令打开Python Shell:

py manage.py shell

试执行以下数据库API:

>>> from polls.models import Choice, Question  # 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)>]>

在这里<Question: Question object (1)>不能提供这个对象的有用信息,可以通过为polls/models.py中的模型增加__str__()方法来解决:

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

再为Question增加一个自定义方法:

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)

执行py manage.py shell打开Python Shell,试执行以下数据库API:

>>> from polls.models import Choice, Question

# 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()

Django管理网站简介

Django根据models自动生成管理网站。

创建管理员账户

执行以下命令,根据提示输入用户名、密码:

py manage.py createsuperuser

启动开发服务器

执行py manage.py runserver命令启动开发服务器,使用浏览器访问http://127.0.0.1:8000/admin/,将看到以下页面:

使用上一步创建的管理员账户登录,即可进入Django管理网站首页。

添加polls应用

首页默认是没有polls应用的,必须修改polls/admin.py文件:

from django.contrib import admin

from .models import Question

admin.site.register(Question)

在浏览器中刷新页面:

点击“Questions”即可对Questions表(polls_question表)进行增删改查等操作。

参考:https://docs.djangoproject/en/2.1/intro/tutorial02/

更多推荐

Django 2.1入门教程(二)