python 的web框架 django 的入门教程2 模型(数据库)

本文是在 python 的web框架 django 的入门教程 1 上开始的。根据 django 官方教程 学习而来,内容也与其教程2配对。

下一节内容是:python 的web框架 django 的入门教程 3 网页(view)

数据库设置

打开 mysite/mysite/settings.py,这是一个普通的Python模块,带有表示Django设置的模块级变量。可以找到数据库的部分,如下:

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

这是缺省数据库的设置,其中包括ENGINE和 NAME。 ENGINE 后指定数据库的类型。我们这里是'django.db.backends.sqlite3',其他还有'django.db.backends.postgresql',  'django.db.backends.mysql', or 'django.db.backends.oracle'对应相应的数据库类别。

我们使用了 Python 内置的 SQLite3 数据库。

SQLite3 是一个十分轻巧的数据库,它仅有一个文件。你可以看一到项目根目录下多出了一个 db.sqlite3 的文件,这就是 SQLite3 数据库文件,django 博客的数据都会保存在这个数据库文件里。

在我们编辑settings.py 时,注意修改语言和时区

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

建立模型

模型建立,对应数据库表的建立。我们这里建立Question和Choice 这2个模型(表)。Question有question和pub_dat 2个字段。 Choisce有2个字段:choice和votes提示。 每个Choice都与一个question相关联。表(table)对应类(class),字段对应成员数据。编辑polls/model.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)

代码很简单。每个模型由类表示,继承自django.db.models.Model。每个模型都有许多类变量,每个类变量代表模型中的数据库字段。

每个字段都由Field类的实例表示-例如,CharField用于字符字段,DateTimeField用于日期时间。这告诉Django每个字段保存什么类型的数据。

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

可以对Field使用可选的第一个位置参数,以指定易于理解的名称。在Django的一些缺省部分中使用了该功能,并且它还作为文档使用。如果未提供此字段,则Django将使用机器可读的名称。在此示例中,我们仅为Question.pub_date定义了易于理解的名称。对于此模型中的所有其他字段,该字段的机器可读名称将足以作为其人类可读的名称。

一些Field类具有必需的参数。例如,CharField要求您给它一个max_length。我们将很快看到,这不仅用于数据库架构,而且用于验证。

字段也可以具有各种可选参数。在这种情况下,我们将votes的默认值设置为0,default=0。

最后,注意使用ForeignKey定义了一个关系。这告诉Django每个选择都与一个问题相关。 Django支持所有常见的数据库关系:多对一,多对多和一对一。

激活模型

回到上面的settings.py 文件,找到上面的INSTALLED_APPS部分,添加一行'polls.apps.PollsConfig'。

要将应用程序包含在项目中,需要在INSTALLED_APPS设置中添加对其配置类的引用。 PollsConfig类位于polls / apps.py文件中,因此其点分路径为“ polls.apps.PollsConfig”。

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

这样django 就知道这个应用了。

运行命令: python manage.py makemigrations polls, 应该看到如下信息:

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

通过运行makemigrations,告诉Django对模型进行了一些更改,并且希望将更改存储为迁移。

运行:python manage.py sqlmigrate polls 0001

将看到一些SQL 命令之类的,这将是要对数据库做的更改,这个命令应该不是必要的,主要是让你看下怎么更改的。

要完成这个更改,需要运行:python manage.py migrate

这就完成了数据库的更改。

现在再归类下我们的操作:

1:更改模型 就是修改models.py文件

2:运行python manage.py makemigrations 给这些更改建立迁移

3:运行python manage.py migrate 将这些更改在数据库里实现

玩玩 API

内容有点长,主要是体验用API。
运行python manage.py shell
进入交互方式
这里注意:>>>后面是输入的,可以复制粘贴,其他#后是说明,其他是运行结果显示

>>> 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 更改如下。注意是更改,添加了一点下面的东西,原来的还要保留。

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

运行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 Admin 介绍

建立一个管理员账户

运行  python manage.py createsuperuser

输入用户名字,然后email ,密码2次:

Username: admin
Email address: [email protected]
Password: **********
Password (again): *********
Superuser created successfully.

启动开发服务器 ,运行:python manage.py runserver

然后浏览器里在本地域名加上/admin ,比如 127.0.0.1:8000/admin

可以看到登陆界面,输入用户名,密码。

login 后可以看到admin 界面,但没有我们的polls。

要告诉admin 你要管理Question。打开polls/admin.py,修改如下:

from django.contrib import admin

from .models import Question

admin.site.register(Question)

现在可以看到POLLS了。

在Questions上点击一下,就进入Questions 的列表,更改页面,你可以直接修改,添加,删除等。

本节内容到此为止,下一节:python 的web框架 django 的入门教程3

发布了131 篇原创文章 · 获赞 112 · 访问量 19万+

猜你喜欢

转载自blog.csdn.net/leon_zeng0/article/details/102904646