django中说的模型(model)就是数据库中的table(表)
django模型文档地址:https://docs.djangoproject.com/zh-hans/5.2/intro/tutorial02/
一、创建模型
模型是在你创建的app目录下的models.py中创建django中模型是以类的形式存在,一个类就是一张表
from django.db import modelsclass Question(models.Model):question_text = models.CharField(max_length=200)pub_date = models.DateTimeField("date published")# def __str__(self):# return '问题表'def __str__(self):return self.question_textclass Choice(models.Model):question = models.ForeignKey(Question, on_delete=models.CASCADE)choice_text = models.CharField(max_length=200)votes = models.IntegerField(default=0)# 解释
1、每个模型都是 django.db.models.Model 类的子类。每个模型有许多类变量,它们都表示模型里的一个数据库字段。
2、每个字段的数据类型都是 Field 类的实例 ,比如,字符字段被表示为 CharField ,日期时间字段被表示为 DateTimeField 。这将告诉 Django 每个字段要处理的数据类型。
3、__str__(self) 这个是返回 self.question_text 这个值,方便辨认
二、激活模型
1、python manage.py makemigrations polls
# 该命令会检测你对模型文件的修改,并且把修改的部分写进迁移文件中。结果会输出以下内容
Migrations for 'polls':polls\migrations\0001_initial.py- Create model Question- Create model Choice这时在你的app目录下的migrations目录下会生成一个迁移文件
0001_initial.py2、python manage.py sqlmigrate polls 0001
该命令会生成0001_initial.py文件中对应的sql语句,
--
-- Create model Question
--
CREATE TABLE `polls_question` (`id` bigint AUTO_INCREMENT NOT NULL PRIMARY KEY, `question_text` varchar(200) NOT NULL, `date published` datetim
e(6) NOT NULL);
--
-- Create model Choice
--
CREATE TABLE `polls_choice` (`id` bigint AUTO_INCREMENT NOT NULL PRIMARY KEY, `choice_text` varchar(200) NOT NULL, `votes` integer NOT NULL, `q
uestion_id` bigint NOT NULL);
ALTER TABLE `polls_choice` ADD CONSTRAINT `polls_choice_question_id_c5b4b260_fk_polls_question_id` FOREIGN KEY (`question_id`) REFERENCES `poll
s_question` (`id`);# 注意:
数据库的表名是由应用名(polls)和模型名的小写形式( question 和 choice)连接而来。(如果需要,你可以自定义表名)这个 sqlmigrate 命令并没有真正在你的数据库中的执行迁移 - 相反,它只是把命令输出到屏幕上,让你看看 Django 认为需要执行哪些 SQL 语句3、python manage.py migrate
# 该命令真正会在数据库中执行对应的sql语句,
Operations to perform:Apply all migrations: admin, auth, contenttypes, polls, sessions
Running migrations:Rendering model states... DONEApplying polls.0001_initial... OK4、python .\manage.py migrate polls
Operations to perform:Apply all migrations: polls
Running migrations:No migrations to apply.
# 如果模型没有更改,可以看到,不会进行重复执行
三、API使用
执行 python manage.py shell 命令进入django命令行,并自动加载当前 Django 项目的环境。
这意味着你可以在这个交互式环境中:
* 直接导入和操作 Django 项目中的模型(Model)
* 调用 Django 的各种功能和 API
* 执行数据库操作(查询、创建、更新、删除数据等)
* 测试代码片段或调试问题