Django2.2丨模型和admin站点

本文详细介绍了在Django2.2中配置数据库、创建和激活模型,以及如何使用初始API和管理页面。从数据库配置、模型定义到数据迁移,再到启动开发服务器和添加管理应用,一步步教你构建Web应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

数据库配置

mysite/settings.py里面包含了Django项目设置的Python模块。

通常,配置文件使用SQLite作为默认数据库。

使用其他数据库,需要安装合适的database bindings,然后改变设置文件中DATABASES 'default’项目中的一些键值:

  • ENGINE :可选值有"django.db.backends.sqlite3’,‘django.db.backendes.postgresql’,‘django.db.backend.mysql’或’django.db.backend.oracle’。其他可用后端。

  • NAME :数据库的名称。如果使用的是SQLite,数据库将是电脑上的一个文件,在这种情况下,NAME应该是此文件的绝对路径,包括文件名。默认值os.path.join(BASE_DIR, ‘db.sqlite3’)将会把数据库文件储存在项目的根目录。

如果不使用SQLite,则必须添加一些额外设置,如USER、PASSWORD、HOST等等。

编辑mysite/settings.py前,需要先设置TIME_ZONE时区。

另外文件头部为INSTALLED_APPS设置项。是包含了项目中所有Django应用。

默认包括Django自带应用。

  • django.contrib.admin:管理员站点
  • django.contrib.auth:认证授权系统
  • django.contrib.contenttypes:内容类型框架
  • django.contrib.sessions:会话框架
  • django.contrib.messages:消息框架
  • django.contrib.staticfiles:管理静态文件的框架

在数据库中创建表的命令

python manage.py migrate

这个migrate命令检查INSTALLED_APPS设置,为其中的每个应用创建需要的数据表。命令所执行的每个迁移操作都会在终端中显示出来。

注:migrate命令只会在INSTALLED_APPS里声明了的应用进行数据库迁移

创建模型

写一个数据库驱动的Web应用的第一步是定义模型-数据库结构设计和附加的其他元数据。

简单的投票应用中,需要创建两个模型:问题Question和选项Choice。Question模型包括问题描述和发布时间。Choice模型有两个字段,选项描述和当前得票数。

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

每个模型有一些类变量,它们都表示模型里的一个数据库字段。

每个字段都是Field类的实例,例:字符字段被表示CharField。

每个Field类实例变量的名字(如question_text)也就是字段名,在数据库会将它们作为列名。

定义某些Field类实例需要参数。例如CharField需要一个max_length参数。这个参数的用处不止于用来定义数据库结构,也用于验证数据。

使用ForeignKey定义了一个关系。这将告诉Django,每个Choice对象都关联到一个Question对象。

Django支持所有常用的数据库关系:多对一、多对多和一对一。

激活模型

首相要把polls应用安装到项目里

需要配置类INSTALLED_APPS中添加设置。因为PollsConfig类写在文件polls/apps.py中,所以它的点式路径式"polls.apps.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',
]

运行命令

python manage.py makemigrations polls

通过运行makemigrations命令,Django会检测对模型文件的修改,并且把修改的部分存储为依次迁移。

迁移是Django对于模型定义的变化的存储形式。

它被存储在polls/migrations/0001)initial.py里。

如果要看看迁移命令执行哪些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)连接而来。
  • 主键(IDs)会被自动创建
  • 默认的,Django会在外键字段名后追加字符串_id。
  • 外键关系由FOREIGN KEY生成。
  • 生成的SQL语句是为自己所用的数据库定制的。
  • 这个sqlmigrate命令并没有真正在数据库中执行迁移,只是把命令输出到屏幕上。

运行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

迁移是非常强大的功能,能在开发过程中持续的改变数据库结构而不需要重新删除和创建表-它专注于使数据库平滑升级而不会丢失数据。

初始API

运行Python命令行

python manage.py shell

使用这个命令而不是简单的使用Python是因为manage.py会设置DJANGO_SETTINGS_MODULE环境变量,这个变量会让Django根据mysite/settings.py文件来设置Python包的导入路径。

>>> 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 object (1)>对于了解这个对象的细节没有什么帮助,可以通过编辑Question模型的代码(位于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
介绍Django管理页面

创建一个管理员账号命令

python manage.py createsuperuser

输入想要使用的用户名、邮箱地址和密码

Username: admin
Email address: admin@example.com
Password: **********
Password (again): *********
Superuser created successfully.
启动开发服务器

Django的管理页面默认就是启用的。

启用命令

python manage.py runserver

进入管理站点页面

使用创建的超级用户来登录,将会看到Django管理页面的索引页。
在这里插入图片描述
它们是由django.contrib.auth提供的。

向管理页面中加入投票应用

只需要做一件事,告诉管理页面,Question对象需要被管理。

# polls/admin.py¶
from django.contrib import admin

from .models import Question

admin.site.register(Question)

在这里插入图片描述

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值