>>> django.VERSION
(4, 1, 0, 'final', 0)
下面使用数据库为Mysql5.7
PS:基于前几章的进度进行修改
Django为这些数据库提供了统一的API
,也就是说我们调用不同的数据库时,只需要使用一种方式即可ORM
,用于实现面向对象编程语言中不同类型系统数据之间的转换
对象关系映射(Object Relational Mapping,简称ORM)
:ORM模式是一种为了解决面向对象与关系数据库存在的互不匹配的现象的技术。简单的说,ORM是通过使用描述对象和数据库之间映射的元数据,将程序中的对象自动持久化到关系数据库中。
优点
:
- 提高开发效率
- 不同数据库可以平滑切换
缺点
:
- ORM代码转换成SQL语句时,需要花费一定的时间,会降低执行效率
- 长期写ORM代码,会降低SQL语句的能力
- ORM会将Python代码转换成SQL语句
- SQL语句通过pymysql传送到数据库服务端
- 在数据库执行SQL语句并且返回结果
settings.py
文件中找到DATABASES
配置项进行修改#这之前先部署一个mysql,创建一个库
mysql> create database test default charset=utf8;
Query OK, 1 row affected, 1 warning (0.00 sec)
#然后再修改
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}
#修改为:
DATABASES = {
'default':
{
'ENGINE': 'django.db.backends.mysql', # 数据库引擎
'NAME': 'test', # 数据库名称
'HOST': '10.10.30.69', # 数据库地址,本机 ip 地址 127.0.0.1
'PORT': 3306, # 端口
'USER': 'root', # 数据库用户名
'PASSWORD': 'fosafer.com', # 数据库密码
}
}
__init__.py
文件,导入mysql模块import pymysql
pymysql.install_as_MySQLdb()
(test) PS F:\django\helloworld> pip install pymysql #安装
Collecting pymysql
Using cached PyMySQL-1.0.2-py3-none-any.whl (43 kB)
Installing collected packages: pymysql
Successfully installed pymysql-1.0.2
WARNING: You are using pip version 22.0.4; however, version 22.2.2 is available.
You should consider upgrading via the 'F:\django\test\Scripts\python.exe -m pip install --upgrade pip' command.
(test) PS F:\django\helloworld> python .\manage.py runserver 0.0.0.0:8000 #启动
Watching for file changes with StatReloader
Performing system checks...
System check identified no issues (0 silenced).
You have 18 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions.
Run 'python manage.py migrate' to apply them. #可以看到这里提示要输入的命令
August 18, 2022 - 11:20:59
Django version 4.1, using settings 'helloworld.settings'
Starting development server at http://0.0.0.0:8000/
Quit the server with CTRL-BREAK.
每个模型都是Python的一个类
,这些类继承django.db.models.Model
。而每个类的属性都相当于是一个数据库的字段,也就是说模型中每个类代表一张表,而类的属性是表的字段
Django规定,如果要使用模型,就必须创建一个app
,使用django-admin startapp TestModel
可以创建一个名叫TestModel
的app
(test) PS F:\django\helloworld> django-admin startapp TestModel
(test) PS F:\django\helloworld> ls
目录: F:\django\helloworld
Mode LastWriteTime Length Name
---- ------------- ------ ----
d----- 2022/8/17 14:17 helloworld
d----- 2022/8/18 10:45 static
d----- 2022/8/17 14:17 templates
d----- 2022/8/18 13:57 TestModel #创建了一个TestModel的目录
-a---- 2022/8/17 10:49 0 db.sqlite3
-a---- 2022/8/17 10:49 688 manage.py
(test) PS F:\django\helloworld> cd TestModel #进入目录
(test) PS F:\django\helloworld\TestModel> ls #查看目录结构
目录: F:\django\helloworld\TestModel
Mode LastWriteTime Length Name
---- ------------- ------ ----
d----- 2022/8/18 13:57 migrations
-a---- 2022/8/18 13:57 66 admin.py
-a---- 2022/8/18 13:57 156 apps.py
-a---- 2022/8/18 13:57 60 models.py
-a---- 2022/8/18 13:57 63 tests.py
-a---- 2022/8/18 13:57 66 views.py
-a---- 2022/8/18 13:57 0 __init__.py
models.py
文件from django.db import models
class Aaa(models.Model):
name = models.CharField(max_length=20)
age = models.CharField(max_legth=3)
解析:
- 上面定义的类名称
Aaa
,代表了数据库的表名- Test类继承了
models.Model
- 类中的字段代表数据表中的字段,也就是
name
,数据类型有CharField(相当于varchar)
、DateField(相当于datetime)
,而max_length
参数用来限定长度最终会创建一个名叫
TestModel_aaa
的表,名称是app+类的名称组成的,表中的字段有name,name字段的数据类型为varchar,限制20个长度,相当于下面的sql语句:注意:如果没有设置主键,那么django会自动添加一个
id
的主键CREATE TABLE TestModel_aaa( "id" serial NOT NULL PRIMARY KEY, "name" varchar(20) NOT NULL, "age" varchar(3) NOT NULL );
- 1
- 2
- 3
- 4
- 5
settings.py
文件使用创建的模型创建模型之后需要告诉Django,在
setting.py
文件中,添加app,添加新创建模型名称即可
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'TestModel', #添加新的app
]
(test) PS F:\django\helloworld> python manage.py migrate #执行对模型修改的操作
- 执行上面的命令后,查看mysql数据库,可以发现已经创建了数据表
mysql> show tables;
+----------------------------+
| Tables_in_test |
+----------------------------+
| auth_group |
| auth_group_permissions |
| auth_permission |
| auth_user |
| auth_user_groups |
| auth_user_user_permissions |
| django_admin_log |
| django_content_type |
| django_migrations |
| django_session |
+----------------------------+
10 rows in set (0.00 sec)
- 下面来创建TestModel模型的表
(test) PS F:\django\helloworld> python manage.py makemigrations TestModel #对操作进行记录,后面可以指定模型
#输出:
- Create model Aaa
(test) PS F:\django\helloworld> python manage.py migrate TestModel #执行对指定模型的修改
#输出:
Applying TestModel.0001_initial... OK
- 再次查看数据库,发现创建了TestModel_aaa 表
mysql> show tables;
+----------------------------+
| Tables_in_test |
+----------------------------+
| TestModel_aaa | #创建的表
| auth_group |
| auth_group_permissions |
| auth_permission |
| auth_user |
| auth_user_groups |
| auth_user_user_permissions |
| django_admin_log |
| django_content_type |
| django_migrations |
| django_session |
+----------------------------+
11 rows in set (0.00 sec)
- 查看表结构,可以看到 id 字段为主键
mysql> show create table TestModel_aaa;
+---------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| Table | Create Table |
+---------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| TestModel_aaa | CREATE TABLE `TestModel_aaa` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`name` varchar(20) NOT NULL,
`age` varchar(3) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 |
+---------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
1 row in set (0.00 sec)
mysql> describe TestModel_aaa;
+-------+-------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------+-------------+------+-----+---------+----------------+
| id | bigint(20) | NO | PRI | NULL | auto_increment |
| name | varchar(20) | NO | | NULL | |
| age | varchar(3) | NO | | NULL | |
+-------+-------------+------+-----+---------+----------------+
3 rows in set (0.00 sec)
HelloWorld
容器目录下添加testdb.py
文件,并修改urls.py
文件- 修改HelloWorld/HelloWorld/urls.py 文件
#-*- coding: utf-8 -*-
from django.urls import path
from . import index_test,testdb #导入模块
urlpatterns = [
path('hello/',index_test.Hello),
path('testdb/',testdb.testdb) #添加新资源
]
- 添加HelloWorld/HelloWorld/testdb.py 文件
#添加数据需要先创建对象,然后执行`save`函数进行保存,相当于`INSERT`SQL语句
# -*- coding: utf-8 -*-
from django.http import HttpResponse
from TestModel.models import Aaa #对应TestModel模型的Aaa类
def testdb(request):
test1 = Aaa(name="zhangsan",age="34") #创建对象,设置对象属性
test1.save()
return HttpResponse("数据添加成功!!!!
")
testdb
(test) PS F:\django\helloworld> python .\manage.py runserver 8000
Watching for file changes with StatReloader
Performing system checks...
System check identified no issues (0 silenced).
August 19, 2022 - 16:33:21
Django version 4.1, using settings 'helloworld.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.
IP:8000/testdb
testdb.py
编写的是插入数据,下面来看查询数据- 修改testdb.py
# -*- coding: utf-8 -*-
from django.http import HttpResponse
from TestModel.models import Aaa
def testdb(request):
response = "" #提前定义空字符串
response_id = ""
response1 = ""
response2 = ""
list = Aaa.objects.all() #查询所有数据行, 相当于 select * from table; 返回一个QuerySet对象,
for i in list:
response1 = i.id
response2 += i.name + " " + i.age + ""
response = response2
response_id = str(response1) #把int类型转换成字符串
return HttpResponse(""
+ response_id + " " + response + "")
IP:8000/testdb
- 现在数据库中,手动增加几条数据,以便看到效果:
mysql> insert into TestModel_aaa values(2,"lisi","22");
Query OK, 1 row affected (0.06 sec)
mysql> insert into TestModel_aaa values(3,"wangwu","55");
Query OK, 1 row affected (0.08 sec)
mysql> select * from TestModel_aaa;
+----+----------+-----+
| id | name | age |
+----+----------+-----+
| 1 | zhangsan | 34 |
| 2 | lisi | 22 |
| 3 | wangwu | 55 |
+----+----------+-----+
3 rows in set (0.00 sec)
- 修改testdb.py
# -*- coding: utf-8 -*-
from django.http import HttpResponse
from TestModel.models import Aaa
def testdb(request):
response = ""
response_id = ""
response1 = ""
response2 = ""
list = Aaa.objects.filter(id=3) #相当于在 select 时添加where过滤
for i in list:
response1 = i.id
response2 += i.name + " " + i.age + ""
response = response2
response_id = str(response1)
return HttpResponse(""
+ response_id + " " + response + "")
# -*- coding: utf-8 -*-
from django.http import HttpResponse
from TestModel.models import Aaa
def testdb(request):
response = ""
response_id = ""
response1 = ""
response2 = ""
list = Aaa.objects.filter(name="lisi")
for i in list:
response1 = i.id
response2 += i.name + " " + i.age + ""
response = response2
response_id = str(response1)
return HttpResponse(""
+ response_id + " " + response + "")
- 修改testdb.py
# -*- coding: utf-8 -*-
from django.http import HttpResponse
from TestModel.models import Aaa
def testdb(request):
list = Aaa.objects.get(id=3)
return HttpResponse(""
+ str(list.id) + list.name + list.age +"")
get
获取的是单个对象,不是可迭代数据,所以可以直接取值,下面来访问一下- 注释
offset 1:表示跳过第1行,因为是根据下标,所以第一行数据行是0开始
limit 2:表示获取前两行
- 下面修改testdb.py文件
# -*- coding: utf-8 -*-
from django.http import HttpResponse
from TestModel.models import Aaa
def testdb(request):
response = ""
response1 = ""
list = Aaa.objects.order_by("name")[0:2] #限制返回的数据,相当于SQL中的offset 0 limit 2,也就是跳过0行,输出前1行
for i in list:
response1 += i.name + " "
response = response1
return HttpResponse(""
+ response + "")
访问,可以看到,显示的是前两行
再次修改进行访问
# -*- coding: utf-8 -*-
from django.http import HttpResponse
from TestModel.models import Aaa
def testdb(request):
response = ""
response1 = ""
list = Aaa.objects.order_by("name")[1:2] #相当于SQL中的offset 1 limit 2,也就是跳过第一行,输出前2行,因为跳过了一行,所以最终输出1行
for i in list:
response1 += i.name + " "
response = response1
return HttpResponse(""
+ response + "")
- 修改testdb.py文件
# -*- coding: utf-8 -*-
from django.http import HttpResponse
from TestModel.models import Aaa
def testdb(request):
response = ""
response_id = ""
response1 = ""
response2 = ""
list = Aaa.objects.order_by("id") #按照指定字段,从小到大排序
for i in list:
response1 += str(i.id)
response2 += i.name + " " + i.age + " "
response = response2
response_id = response1
return HttpResponse(""
+ response_id + " " + response + "")
访问
上面是从小到大,下面是从大到小
- 修改testdb.py文件
# -*- coding: utf-8 -*-
from django.http import HttpResponse
from TestModel.models import Aaa
def testdb(request):
response = ""
response_id = ""
response1 = ""
response2 = ""
list = Aaa.objects.order_by("-id") #按照指定字段,从小到大排序,前面加 -
for i in list:
response1 += str(i.id)
response2 += i.name + " " + i.age + " "
response = response2
response_id = response1
return HttpResponse(""
+ response_id + " " + response + "")
- 往数据库添加数据
mysql> insert into TestModel_aaa values(4,"lisi","22");
Query OK, 1 row affected (0.15 sec)
mysql> select * from TestModel_aaa;
+----+----------+-----+
| id | name | age |
+----+----------+-----+
| 1 | zhangsan | 34 |
| 2 | lisi | 22 |
| 3 | wangwu | 55 |
| 4 | lisi | 22 |
+----+----------+-----+
4 rows in set (0.00 sec)
- 修改testdb.py文件
# -*- coding: utf-8 -*-
from django.http import HttpResponse
from TestModel.models import Aaa
def testdb(request):
response = ""
response_id = ""
response1 = ""
response2 = ""
list = Aaa.objects.filter(name="lisi").order_by("id") #where查询name等于lisi的,然后通过id进行从小大到大排序
for i in list:
response1 += str(i.id)
response2 += i.name + " " + i.age + " "
response = response2
response_id = response1
return HttpResponse(""
+ response_id + " " + response + "")
- 修改testdb.py文件
# -*- coding: utf-8 -*-
from django.http import HttpResponse
from TestModel.models import Aaa
def testdb(request):
test1 = Aaa.objects.get(id=1) #获取id为1的数据行作为单个对象
test1.name = "liuliu" #修改对象的name字段为liuliu,也就是修改对象的属性
test1.save() #最后保存
return HttpResponse("修改成功
")
- 修改testdb.py
# -*- coding: utf-8 -*-
from django.http import HttpResponse
from TestModel.models import Aaa
def testdb(request):
Aaa.objects.filter(id=2).update(name="wuwuwu") #利用filter筛选数据行,然后使用update方法直接修改指定字段
return HttpResponse("修改成功
")
filter
那么修改全部就是all
- 修改testdb.py
# -*- coding: utf-8 -*-
from django.http import HttpResponse
from TestModel.models import Aaa
def testdb(request):
Aaa.objects.all().update(age="120")
return HttpResponse("全部修改成功
")
删除数据和修改数据差不多,只不过是把update
换成delete
,下面直接来看两种方法
一种,先取出指定对象,然后删除
- 修改testdb.py
# -*- coding: utf-8 -*-
from django.http import HttpResponse
from TestModel.models import Aaa
def testdb(request):
test1 = Aaa.objects.get(id=1)
test1.delete()
return HttpResponse("删除成功!!
")
delete
方法删除- 修改testdb.py
# -*- coding: utf-8 -*-
from django.http import HttpResponse
from TestModel.models import Aaa
def testdb(request):
Aaa.objects.filter(id=2).delete()
return HttpResponse("删除成功!!
")
- 修改testdb.py
# -*- coding: utf-8 -*-
from django.http import HttpResponse
from TestModel.models import Aaa
def testdb(request):
Aaa.objects.all().delete()
return HttpResponse("删除全部成功!!
")