文章目录

数据库设置

打开mysite/settings.py.这是一个普通的Python模块,其中的模块级变量代表Django设置。
默认情况下,配置使用SQLite。
如果您希望使用其他数据库,请安装相应的数据库绑定,并在DATABASES '默认’项目中更改以下键以匹配您的数据库连接设置:

  • ENGINE – 下面中的任一一种’django.db.backends.sqlite3’, ‘django.db.backends.postgresql’, ‘django.db.backends.mysql’, 或’django.db.backends.oracle’。 这四种是官方支持的数据库,其他后端也可以通过第三方支持来使用,具体查看https://docs.djangoproject.com/en/2.1/ref/databases/#third-party-notes。
  • NAME –你数据库的名称 如果你使用的是的SQLite, 数据库就是你电脑上的一个文件; 在这种情况下, NAME 应该设置为一个完整的绝对路径, 包括文件名。默认值是os.path.join(BASE_DIR, ‘db.sqlite3’),将会把文件存储在您的项目目录中。
    如果您不使用SQLite作为数据库,则必须添加其他设置,例如USER,PASSWORD和HOST。

在编辑mysite/settings.py时,将TIME_ZONE设置为您的时区。

另外,请注意文件顶部的INSTALLED_APPS设置。 它包含在此Django实例中激活的所有Django应用程序的名称。 应用程序可以用于多个项目,您可以打包并分发这些应用程序以供他人在其项目中使用。

默认情况下,INSTALLED_APPS包含以下应用程序,这些应用程序都是Django附带的:

  • django.contrib.admin - admin网站。 你会很快使用它。
  • django.contrib.auth - 认证系统。
  • django.contrib.contenttypes - 内容类型的框架。
  • django.contrib.sessions - 会话框架。
  • django.contrib.messages - 一个消息框架。
  • django.contrib.staticfiles - 管理静态文件的框架。

其中一些应用程序至少使用了一个数据库表,所以我们需要在数据库中创建表格,然后才能使用它们。 为此,请运行以下命令:

$ python manage.py migrate
python3 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 admin.0003_logentry_add_action_flag_choices... 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

migrate命令查看INSTALLED_APPS设置,并根据mysite/settings.py文件中的数据库设置创建所有必要的数据库表。(The migrate command looks at the INSTALLED_APPS setting and creates any necessary database tables according to the database settings in your mysite/settings.py file and the database migrations shipped with the app (we’ll cover those later). )

创建模型

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)

每个模型都由一个子类来表示django.db.models.Model. 每个模型都有许多类变量,每个变量表示模型中的数据库字段。

每个字段都由一个字段类的实例Field表示——例如,用于字符字段的CharField和DateTimeField。 这告诉Django每个字段拥有什么类型的数据。

每个Field实例(例如question_text或pub_date)的名称是机器友好格式的字段名称。 您将在您的Python代码中使用此值,并且您的数据库将使用它作为列名称。

您可以使用可选的第一个位置参数指向一个字段来指定一个人类可读的名称。在这个例子中,我们只为Question.pub_date定义了一个人类可读的名字。

一些Field类具有必需的参数。 CharField, 例如,需要你给它一个 max_length. 这不仅在数据库模式中使用,而且在验证中使用,我们很快就会看到。

一个Field也可以有各种可选的参数;在这种情况下,我们已将votes的default值设置为0。

最后,请注意使用ForeignKey定义关系。 这告诉Django每个Choice都与单个Question有关(多对一)。 Django支持所有常见的数据库关系:多对一,多对多和一对一。

激活模型

首先我们需要告诉我们的项目安装了polls应用程序。
要将该应用程序包含在我们的项目中,我们需要在INSTALLED_APPS设置中添加对其配置类的引用。 PollsConfig类位于polls/apps.py文件中,因此它的虚线路径为’polls.apps.PollsConfig’。 编辑mysite/settings.py文件并将该点标识路径添加到INSTALLED_APPS设置中。 它看起来像这样:

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

现在Django知道包含polls应用程序。 让我们运行另一个命令:

$ python manage.py makemigrations polls

您应该看到类似于以下内容的内容:

python3 manage.py makemigrations polls
Migrations for 'polls':
  polls/migrations/0001_initial.py
    - Create model Choice
    - Create model Question
    - Add field question to choice

再次运行migrate以在您的数据库中创建这些模型表:

python3 manage.py migrate
Operations to perform:
  Apply all migrations: admin, auth, contenttypes, polls, sessions
Running migrations:
  Applying polls.0001_initial... OK

migrate命令采用所有尚未应用的迁移(Django使用名为django_migrations的数据库中的特殊表来跟踪哪些应用),并根据您的数据库运行它们实质上,将您对模型所做的更改与数据库中的模式同步。

迁移非常强大,随着时间的推移,您可以随时更改模型,而无需删除数据库或表并创建新的数据库 - 它专门用于实时升级数据库,而不会丢失数据。 我们将在本教程的后面部分更深入地介绍它们,但现在请记住进行模型更改的三步指南:

  • 更改模型(在models.py中)。
  • 运行python manage.py makemigrations为这些更改创建迁移
  • 运行python manage.py migrate,将这些更改应用到数据库。

使用单独的命令来生成和应用迁移,因为您将迁移到您的版本控制系统并将它们与您的应用程序一起发送;它们不仅使您的开发更容易,而且还可以被其他开发人员和生产使用。

玩转API

现在,让我们进入交互式Python shell并使用Django提供的API。 要调用Python shell,请使用以下命令:

$ python manage.py shell

我们使用这个命令而不是简单地输入"python"命令是因为 manage.py 将 DJANGO_SETTINGS_MODULE 设置为环境变量, 它将Python 文件mysite/settings.py 的引入路径告诉Django.

>>> from polls.models import Question, Choice   # 将我们刚刚写好的模型类引入.

# No questions are in the system yet.
>>> Question.objects.all()
<QuerySet []>

# 创建一个新的调查问题.
# 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)> 不是这个对象的有效表现形式。 我们通过编辑Question模型(polls/models.py文件中)并添加一个__str__()方法来修复Question和Choice:

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 __()方法很重要,不仅为了您在处理交互提示时的方便,还因为在Django自动生成的管理中使用了对象表示。

请注意,这些是普通的Python方法。 让我们添加一个自定义方法,仅供演示:

def was_published_recently(self):
        return self.pub_date >= timezone.now() - datetime.timedelta(days=1)

再次运行python manage.py shell,保存这些更改并启动一个新的Python交互式shell:

>>> from polls.models import Question, Choice

# 确认我们的 __str__() 方法已经正常工作.
>>> Question.objects.all()
<QuerySet [<Question: What's up?>]>

# Django 提供了丰富的数据库查询API通过
# 关键字参数来驱动
>>> Question.objects.filter(id=1)
<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.get(pub_date__year=current_year)
<Question: What's up?>

# 查询一个不存在的ID时会引发一个异常
>>> 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 Admin

1、创建超级管理员:

python3 manage.py createsuperuser
Username (leave blank to use 'fww'): admin
Email address: admin@example.com
Password:
Password (again):
This password is too short. It must contain at least 8 characters.
This password is too common.
This password is entirely numeric.
Bypass password validation and create user anyway? [y/N]: N
Password:
Password (again):
This password is too common.
This password is entirely numeric.
Bypass password validation and create user anyway? [y/N]: y
Superuser created successfully.

2、启动服务器:

$ python manage.py runserver

在浏览器地址栏输入:http://127.0.0.1:8000/admin/, 你就可以看到管理员登录界面了。输入用户名和密码,你应该看到Django管理索引页面。您应该看到几种可编辑的内容:组和用户。 它们由Django提供的认证框架django.contrib.auth提供。

3、在admin中修改poll应用程序
但是我们的民意调查程序在哪里? 它并没有显示在管理索引页面上。

为此需要做的是: 我们需要网站控制台 Question 对象有一个管理接口, 要做到这点,打开polls/admin.py文件,并编辑成:

from django.contrib import admin

# Register your models here.
from .models import Question

admin.site.register(Question)

现在我们已经注册了Question,Django知道它应该显示在管理索引页面上.

10-07 09:01