上一篇文章进行到在Windows10+python3.8+pycharm的环境下利用Django框架创建了一个默认项目,成功运行后又添加了一个很简单的实例应用
不过这个简单应用是静态的,不可能放在实际的应用场景中。所以上一步只是了解了Django基本的请求和响应流程。
此图是官方文档为数据库配置的说明:通常,这个配置文件使用 SQLite 作为默认数据库。如果你想使用其他数据库,你需要安装合适的 database bindings ,然后改变设置文件中 DATAbaseS ‘default’ 项目中的一些键值。
python3 manage.py migrate
此处这个 migrate 命令检查 INSTALLED_APPS 设置,为其中的每个应用创建需要的数据表,至于具体会创建什么,这取决于你的 mysite/settings.py 设置文件和每个应用的数据库迁移文件
从命令行端看到应用所有迁移:管理、身份验证、内容类型、会话
跟随官方的例子
创建了投票应用polls
然后设置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)
3.激活模型
这一步能帮助理解Django中迁移的概念:迁移是非常强大的功能,它能让你在开发过程中持续的改变数据库结构而不需要重新删除和创建表
在mysite项目中添加polls应用,我们需要在配置类 INSTALLED_APPS 中添加设置
python3 manage.py makemigrations polls
运行 makemigrations 命令,Django 会检测你对模型文件的修改(在这种情况下,你已经取得了新的),并且把修改的部分储存为一次 迁移。
python3 manage.py sqlmigrate polls 0001
sqlmigrate 命令接收一个迁移的名称,然后返回对应的 SQL
结果
C:Users86150Desktop我的PYTHON项目mysite>python3 manage.py makemigrations polls
Migrations for 'polls':
pollsmigrations0001_initial.py
- Create model Question
- Create model Choice
C:Users86150Desktop我的PYTHON项目mysite>python3 manage.py sqlmigrate polls 0001
BEGIN;
--
-- Create model Question
--
CREATE TABLE "polls_question" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "question_text" varchar(200) NOT NULL, "pub_date" d
atetime NOT NULL);
--
-- Create model Choice
--
CREATE TABLE "polls_choice" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "choice_text" varchar(200) NOT NULL, "votes" integer NOT NULL, "question_id" integer NOT NULL REFERENCES "
polls_question" ("id") DEFERRABLE INITIALLY DEFERRED);
CREATE INDEX "polls_choice_question_id_c5b4b260" ON "polls_choice" ("question_id");
COMMIT;
小回顾
改变模型需要这三步:
编辑 models.py 文件,改变模型。
运行 python manage.py makemigrations 为模型的改变生成迁移文件。
运行 python manage.py migrate 来应用数据库迁移。
python3 manage.py shell
使用这个命令而不是简单的使用 “Python” 是因为 manage.py 会设置 DJANGO_SETTINGS_MODULE 环境变量,这个变量会让 Django 根据 mysite/settings.py 文件来设置 Python 包的导入路径。
C:Users86150Desktop我的PYTHON项目mysite>python3 manage.py shell Python 3.8.2 (tags/v3.8.2:7b3ab59, Feb 25 2020, 22:45:29) [MSC v.1916 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. (InteractiveConsole) >>> from polls.models import Choice, Question >>> Question.objects.all()>>> from django.utils import timezone >>> q = Question(question_text="What's new?", pub_date=timezone.now()) >>> q.save() >>> q.id 1 >>> q.question_text "What's new?" >>> q.pub_date datetime.datetime(2021, 10, 8, 13, 5, 8, 644672, tzinfo= ) >>> q.question_text = "What's up?" >>> q.save() >>> Question.objects.all() ]> >>> ^Z
然后还可以在应用的models里面添加一些方法,



