Django教程二

数据库设置

现在,打开mysite/settings.py。这是一个普通的Python模块,其中模块级变量代表Django设置。

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

python manage.py migrate

该migrate命令查看INSTALLED_APPS设置并根据mysite/settings.py文件中的数据库设置和应用程序附带的数据库迁移创建任何必要的数据库表(稍后我们将介绍这些表)。您将看到适用于每次迁移的消息。如果您有兴趣,请运行数据库的命令行客户端并键入\dt(PostgreSQL),(MySQL), (SQLite)或(Oracle)以显示Django创建的表。

创建模型

在我们简单的民意调查应用程序中,我们将创建两个模型:Question和Choice。A Question有问题和出版日期。A Choice有两个字段:选择的文本和投票记录。每个Choice都与一个Question。

这些概念由简单的Python类表示。编辑 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)

激活模型

要在我们的项目中包含应用程序,我们需要在设置中添加对其配置类的引用INSTALLED_APPS。该 PollsConfig班是在polls/apps.py文件中,所以它的虚线路径’polls.apps.PollsConfig’。编辑mysite/settings.py文件并将该虚线路径添加到INSTALLED_APPS设置中。它看起来像这样:

INSTALLED_APPS = [
    'polls.apps.PollsConfig',
    '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

有一个命令可以为您运行迁移并自动管理您的数据库模式 - 这是被调用的migrate,我们马上就会看到它 - 但首先,让我们看看迁移将运行的SQL。该 sqlmigrate命令获取迁移名称并返回其SQL:

python manage.py sqlmigrate polls 0001

请注意以下事项:

  • 确切的输出将根据您使用的数据库而有所不同。上面的示例是为PostgreSQL生成的。

  • 表名是通过组合应用程序的名称(自动生成polls)和模型的小写名字- question和 choice。(您可以覆盖此行为。)

  • 主键(ID)会自动添加。(你也可以覆盖它。)

  • 按照惯例,Django附加"_id"到外键字段名称。(是的,你也可以覆盖它。)

  • 外键关系通过 约束显式化。不要担心零件; 这只是告诉PostgreSQL在事务结束前不强制执行外键。FOREIGN KEYDEFERRABLE

  • 它是根据您正在使用的数据库量身定制的,因此可以自动为您处理特定于数据库的字段类型,如auto_increment(MySQL),serial(PostgreSQL)或(SQLite)。引用字段名称也是如此 - 例如,使用双引号或单引号。integer primary key autoincrement

  • 该sqlmigrate命令实际上并不在您的数据库上运行迁移 - 它只是将其打印到屏幕上,以便您可以看到SQL Django认为需要什么。它对于检查Django将要执行的操作或者是否有需要SQL脚本进行更改的数据库管理员非常有用。

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

>>> python manage.py migrate
Operations to perform:
  Apply all migrations: admin, auth, contenttypes, polls, sessions
Running migrations:
  Rendering model states... DONE
  Applying polls.0001_initial... OK

使用

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

python manage.py shell

进入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)>Questionpolls/models.py__str__()QuestionChoice.
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()向模型添加方法非常重要,不仅是为了您在处理交互式提示时的方便,还因为在Django自动生成的管理中使用了对象的表示。

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

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的标准模块和Django的时区相关实用程序。如果您不熟悉Python中的时区处理,可以在时区支持文档中了解更多信息。
import datetimefrom django.utils
import timezonedatetimedjango.utils.timezone

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

>>> 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管理员

创建管理员用户

首先,我们需要创建一个可以登录管理站点的用户。运行以下命令:

python manage.py createsuperuser

输入所需的用户名,然后按Enter键。

Username: admin

然后,系统将提示您输入所需的电子邮件地址:

Email address: admin@example.com

最后一步是输入密码。系统会要求您输入两次密码,第二次输入密码作为第一次确认。

Password: **********
Password (again): *********
Superuser created successfully.

启动admin服务器

Django管理站点默认激活。让我们启动开发服务器并进行探索。

如果服务器没有运行,请启动它:

python manage.py runserver

在管理员中修改民意调查应用程序

但是我们的投票应用程序在哪里?它不会显示在管理员索引页面上。

只需做一件事:我们需要告诉管理员Question 对象有一个管理界面。为此,请打开该polls/admin.py 文件,然后将其编辑为如下所示:

from django.contrib import admin

from .models import Question

admin.site.register(Question)

未完待续…

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值