Django基础2-模型和管理站点

版权声明:本文为博主原创文章,欢迎转载。 https://blog.csdn.net/fww330666557/article/details/82955549

DATABASES

打开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。
**注意:**
如果你使用SQLite之外的数据库,请确保你已经创建了一个数据库。 
还要确保mysite/settings.py中提供的数据库用户具有“创建数据库”权限。 这允许自动创建一个测试数据库,这将在稍后的教程中需要。
如果您使用的是SQLite,则无需事先创建任何内容 - 数据库文件将在需要时自动创建。

INSTALLED_APPS

文件顶部的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). )

**个人理解**
这块的译文和原文都不好理解,我自己的当前理解大概意思是:migrate命令会根据数据库设置和应用模型自动创建数据库表。
**对于极简主义者**
就像我们上面所说的那样,默认应用程序包含在常见的情况下,但不是每个人都需要它们。 如果您不需要其中任何一个或全部,请在运行migrate之前自由注释或删除INSTALLED_APPS中的相应行。 migrate命令将只对INSTALLED_APPS中的应用程序进行迁移。

**个人理解**
按照python的哲学,不需要的东西当然应该清理掉。有一个疑问是,比如按照原来的INSTALLED_APPS设置已经运行了migrate命令,后年如果发现有某个应用其实是不需要的,那么,清理掉不需要的设置之后,再次运行migrate命令,会不会自动清除掉数据库中已经创建的表?这有待验证。

创建模型

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的一个子类, 每个模型类都包含一些类变量,每个类变量表示模型中的数据库字段。

每个字段都是一个字段类的实例——例如,用于字符字段的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支持所有常见的数据库关系:多对一,多对多和一对一。

激活模型

**哲学:**
Django应用程序是“可插入的”:您可以在多个项目中使用应用程序,并且可以分发应用程序,因为它们不必绑定到给定的Django安装。

在INSTALLED_APPS设置中添加对APP配置类的引用

要将该应用程序包含在我们的项目中,我们需要在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

通过运行makemigrations,您告诉Django您已经对模型进行了一些更改(这里,你创建了新的模型),并且您希望将更改存储为一个migration。
Migrations是Django存储模型和数据库表更改的方式,它们实质上就是磁盘上的文件。如果你喜欢,你可以阅读新模型的migration;它是文件polls/migrations/0001_initial.py。别担心,你并不需要去读它们,只是它们被设计是可人为编辑的,这可能会在需要手动微调时用到。
migrate命令为你运行Migrations,并且自动管理数据库表。首先我们来看看migrate命令执行了哪些SQL语句:

$ python manage.py sqlmigrate polls 0001

你将会看到类似如下的内容:

BEGIN;
--
-- Create model Choice
--
CREATE TABLE "polls_choice" (
    "id" serial NOT NULL PRIMARY KEY,
    "choice_text" varchar(200) NOT NULL,
    "votes" integer NOT NULL
);
--
-- Create model Question
--
CREATE TABLE "polls_question" (
    "id" serial NOT NULL PRIMARY KEY,
    "question_text" varchar(200) NOT NULL,
    "pub_date" timestamp with time zone NOT NULL
);
--
-- Add field question to choice
--
ALTER TABLE "polls_choice" ADD COLUMN "question_id" integer NOT NULL;
ALTER TABLE "polls_choice" ALTER COLUMN "question_id" DROP DEFAULT;
CREATE INDEX "polls_choice_7aa0f6ee" ON "polls_choice" ("question_id");
ALTER TABLE "polls_choice"
  ADD CONSTRAINT "polls_choice_question_id_246c99a640fbbd72_fk_polls_question_id"
    FOREIGN KEY ("question_id")
    REFERENCES "polls_question" ("id")
    DEFERRABLE INITIALLY DEFERRED;

COMMIT;

清注意以下几点:

  • 确切的输出将取决于您使用的数据库。
  • 表名是通过将应用程序的名称(polls)和模型的小写名称question和choice组合自动生成的。 (您可以覆盖此行为。)
  • 主键(ID)会自动添加。 (你也可以覆盖它。)
  • 按照惯例,Django将“_id”附加到外键字段名称。 (是的,你也可以重写这个。)
  • 外键关系通过FOREIGN KEY约束来显式化。 不要担心DEFERRABLE部分;这只是告诉PostgreSQL在事务结束之前不执行外键。
  • 因为输出将取决于您使用的数据库,因此对于数据库的特有字段,如auto_increment(MySQL),serial(PostgreSQL)或integer primary key autoincrement(SQLite),都会为你自动处理。双引号或单引号内的字段名称也是如此。
  • sqlmigrate命令实际上并不在数据库上运行迁移 - 它只是将它打印到屏幕上,以便您可以看到SQL Django认为需要什么。 这对于检查Django将要做什么或者如果您有需要SQL脚本进行更改的数据库管理员很有用。

如果您有兴趣,您也可以运行

python manage check 

这可以检查项目中的任何问题,而无需进行迁移或接触数据库。

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

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

migrate 命令 读取所有尚未应用的migrations (Django使用名为django_migrations的数据库中的特殊表来跟踪哪些migrations已经被应用) 并且, 运行与数据库中的记录相反的那些migrations- 大体上, 就是将你对模型所做的更改与数据库中的表进行同步。

***上一段原文***
The migrate command takes all the migrations that haven’t been applied (Django tracks which ones are applied using a special table in your database called django_migrations) and runs them against your database - essentially, synchronizing the changes you made to your models with the schema in the database.

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

  • 更改模型(在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

**哲学**
为您的员工或客户生成管理网站以添加,更改和删除内容是一项繁琐的工作,无需太多创造性。 出于这个原因,Django完全自动为模型创建管理界面。

Django是在新闻编辑室编写的,在“内容发布者”和“公共”网站之间有着非常明确的分离。 网站管理员使用该系统添加新闻报道,事件,体育比分等,并且该内容显示在公共站点上。 Django解决了为站点管理员创建统一界面以编辑内容的问题。

管理界面不向普通用户开放。 只提供给网站管理者

1、创建管理员用户:

python3 manage.py createsuperuser
Username (leave blank to use 'fww'): admin
Email address: [email protected]
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.

然后,启动开发服务器:

$ python manage.py runserver

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

由于自动翻译默认情况下处于打开状态,因此登录界面可能会以您自己的语言显示,具体取决于您的浏览器设置,以及Django是否具有该语言的翻译。

2、在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知道它应该显示在管理索引页面上.

猜你喜欢

转载自blog.csdn.net/fww330666557/article/details/82955549
今日推荐